Reputation: 3105
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
Thanks!
Upvotes: 1
Views: 227
Reputation: 12699
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)
Upvotes: 4
Reputation: 2550
Looking at the code of mongoid 2.0 has_many_related is just an alias to has_many:
➜ mongoid git grep has_many_related
lib/ mongoid/relations/macros.rb: alias :has_many_related :has_many
Just change it to :has_many and keep the code the same. There's an example of a block given to :has_many in the Mongoid Documentation here
Upvotes: 2