我遇到了一个问题,我试图从注释模型中引用两次名为user的模型。
第一种情况是因为用户可以有很多评论(作为接收者)
但另一个联想是一个评论有一个作者。是这样吗?
references_one :user, :inverse_of :author那么,我是否需要在用户中为该用户的评论添加另一个关联,而不是该用户的评论。
embedded_in :user, :inverse_of => :commentsout我希望这有点道理。
也许这样的代码更有意义(伪代码)
user:
has_many: comments => author
can_be: author, recipient
comment:
belongs_to_many: users => recipients
has_one: user => author发布于 2011-02-19 03:37:45
如果我对这个问题的理解是正确的,那么您可以这样定义关联:
class User
include Mongoid::Document
field :name, :type => String
references_many :comments, :inverse_of => :author
references_and_referenced_in_many :comments_received, :class_name => 'Comment', :inverse_of => :recipients
end
class Comment
include Mongoid::Document
field :text, :type => String
referenced_in :author, :class_name => 'User'
references_and_referenced_in_many :recipients, :class_name => 'User', :inverse_of => :comments_received
end如果无法从关联名称推断出目标,则需要添加一个:class_name参数。这使得对同一个类有多个关联成为可能。
https://stackoverflow.com/questions/5035597
复制相似问题