Two 1 - N relations in Mongoid (Rails)

ⅰ亾dé卋堺 提交于 2019-12-03 14:20:24
Steve

You can achieve what you want using the class_name and inverse_of options:

class Account
  include Mongoid::Document
  field :name
  has_many :ratings_given, :class_name => 'Ratings', :inverse_of => :rater
  has_many :my_ratings, :class_name => 'Ratings', :inverse_of => :ratee
end

class Ratings
  include Mongoid::Document
  field :name
  belongs_to :rater, :class_name => 'Account', :inverse_of => :ratings_given
  belongs_to :ratee, :class_name => 'Account', :inverse_of => :my_ratings
end

The documentation has changed since I was last working with it so I wasn't sure whether this is still the recommended approach. Looks like it doesn't mention these options on the 1-many referenced page. But if you take a look at the general page on relations they are covered there.

In any case you need to explicitly link ratings_given/rater and my_ratings/ratee associations when there are two associations to the same class, otherwise mongoid has no way to know which of the two potential inverses to pick.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!