5

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 :)

1 Answer 1

10

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.

For more clarity, assume embedded document as a field in the parent document which contains sub fields. Now you can easily understand that you cannot save a field without a document. right?

Other hand new  initialize the document class and will be only inserted into the parent doc when using <<.

Category.create(:name => "party")
>>NoMethodError: undefined method `new?' for nil:NilClass

is equivalent to

 c = Category.new(:name => "party")
 c.save
 >>NoMethodError: undefined method `new?' for nil:NilClass

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.