How do you use the has_many_related relationship in mongoid 3+?
I am currently migrating from mongoid 2.0 to mongoid 3.0.5. One of the relationships I have in an object is a has_many_related. How do I migrate this over to mongoid 3.0.5? I couldn't find any documentation for this via google searches, or in the mongoid.org and the two.mongoid.org websites. Is there someplace I should be looking?
Here is the code:
has_many_related :food_review do def find_or_initialize_by_user_id(user_id) criteria.where(:user_id => user_id).first || build(:user_id => user_id) end end
Just use has_many instead of has_many_related.
For example :
class User include Mongoid::Document field :name, type: String field ... has_many :food_reviews def find_or_initialize_by_user_id(user_id) criteria.where(:user_id => user_id).first || build(:user_id => user_id) end end class FoodReview include Mongoid::Document field ... belongs_to :user end
note the plural has_many :food_reviews and the singular class FoodReview. If you want to refer a singular review, just use has_one :food_review (see Referenced 1-1)