Mongoid:对 MongoDB 的评论和用户对 MySQL 的评论?如何让它发挥作用
我想创建一个同时使用 MongoDB 和 MySQL 的应用程序。具体来说,我希望 mongodb 存储所有用户的评论,而 MySQL 存储用户模型。
class User < ActiveRecord::Base
has_many :comments
end
class Comment
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user
end
好吧,一切看起来都很好,除了当我转到 Rails 控制台并运行它时。
k = Comment.new
k.user = User.first
我得到了
NoMethodError: 用户加载 (0.3ms) SELECT
users
.* FROMusers
WHEREusers
._id
= 1 Mysql2::Error:未知列“users._id” ‘where 子句’: SELECTusers
.* FROMusers
WHEREusers
._id
= 1 未定义方法“from_map_or_db”
看起来:=
方法正在寻找模型的_id
而不是id
?是否有解决方法可以使其自动工作,或者我是否需要创建自己的 =
方法? 以前有人尝试过相同的配置吗?如果是这样,让所有这些发挥作用的步骤是什么?
I want to create an app that uses both MongoDB and MySQL. Specifically, I want mongodb to store all the users' comments while MySQL will store the User model.
class User < ActiveRecord::Base
has_many :comments
end
class Comment
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user
end
well, everything looks good except when I go to the rails console and run this.
k = Comment.new
k.user = User.first
I got
NoMethodError: User Load (0.3ms) SELECT
users
.* FROMusers
WHEREusers
._id
= 1 Mysql2::Error: Unknown column 'users._id' in
'where clause': SELECTusers
.* FROMusers
WHEREusers
._id
= 1
undefined method `from_map_or_db' for
It looks like that the :=
method is looking for the _id
of the model instea of the id
? Is there a workaround to get this working automatically or do I need to create my own =
method?
Has anyone tried the same configuration before? If so, what are the steps to get all these to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不会像你想要的那样工作。
Comment
中的belongs_to :user
告诉 Mongoid 在 MongoDB 中建立此关联;为了建立 ActiveRecord 关联,您的类必须继承ActiveRecord::Base
或包含ActiveRecord::Model
- 并且您不能同时执行这两种操作!可能最好的方法是编写您自己的方法将
Users
和Comments
关联在一起(我不知道这会有多困难)。This is not gonna work like you want it to. Your
belongs_to :user
inComment
is telling Mongoid to make this association in MongoDB; in order to make ActiveRecord associations, your class must inherit fromActiveRecord::Base
or includeActiveRecord::Model
--and you can't do both!Probably the best way to do this--and I don't know how difficult it would be--is to write your own methods to associate the
Users
andComments
together.您可以尝试使用关联表:
我目前没有任何方法来测试它,但是它可能会起作用。您的思维模型将需要 user_id 和 _id 列。
You might try an association table:
I don't have any way of testing this at the moment but, it may work. Your thought model will need user_id and _id columns.