Two 1 - N relations in Mongoid (Rails)

2019-03-28 05:48发布

问题:

The scenario is:

How can an Account give ratings to another account? This results in two lists on the Account. Those who I have rated and those who have rated me. (my_ratings and ratings_given)

This boils down to:

How can multiple 1 - N relationsips to the same entity work in Mongoid?

In Mongoid's Docs it says you can use has_many and belongs_to to link the entities together.

I currently have this on Account

  has_many :ratings, :as => "my_ratings"
  has_many :ratings, :as => "ratings_given"

and this on Ratings:

 belongs_to :user, :as => 'Rater'
 belongs_to :user, :as => 'Ratie'

The docs don't cover this case, so I thought you would have to differentiate between the two with an :as parameter.

Is this even remoting correct?

回答1:

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.