Mongoid协会

时间:2011-02-17 22:38:40

标签: ruby-on-rails mongoid

我遇到了一个问题,我试图从评论模型中引用一个名为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

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,你可以定义这样的关联:

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参数。这使得可以与同一个类具有多个关联。

相关问题