Two 1 - N relationships in Mongoid (Rails)

Scenario:

How can an account assign ratings to another account? This results in two lists on the Account. Those whom I appreciated, and those who appreciated me. (my_ratings and ratings_given)

It comes down to:

How do multiple 1 - N relationships with the same object work in Mongoid?

Mongoid Docs says you can use has_many and belongs_to to bind entities together.

I currently have this on my Account

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

and this is on Ratings :

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

Documents do not cover this case, so I thought you would have to distinguish between two parameters: how.

Is it removed correctly?

+6
source share
1 answer

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 the last time I worked with it, so I was not sure if this is still recommended. It seems that these options are not mentioned on page 1- many links. But if you look at the general relations page , they will be covered there.

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

+18
source

Source: https://habr.com/ru/post/890809/


All Articles