I have following User model, embeds the Category model,
class User
include Mongoid::Document
include BCrypt
field :email, :type => String
field :password_hash, :type => String
field :password_salt, :type => String
embeds_many :categories
embeds_many :transactions
....
end
My question is, I just found that if I use the code:
me = User.where("some conditions")
me.categories << Category.new(:name => "party")
everything works fine, but if I use the .create method:
me = User.where("some conditions")
me.categories << Category.create(:name => "party")
I will get an exception:
undefined method `new?' for nil:NilClass
Anyone knows why is that? And from mongoid.org http://mongoid.org/docs/persistence/standard.html, I could see that .new and .create actually generates the same mongo command.
Needs help, thanks 🙂
Create immediately persist the document into mongo. Since the category document is within another document (as embedded) you cannot save it separately. Thats why you are getting the error.
Other hand new initialize the document class and will be only inserted into the parent doc when using <<.
is equivalent to
Hope this helps