Search code examples
ruby-on-railsmongodbmongoidembeddingdatabase-relations

Mongoid Create Embedded Document Inside Parent


I have two models User and Status. Status is embedded in User:

User.rb

class User

  include Mongoid::Document
  include Mongoid::Timestamps

  embeds_one :status, as: :statusable

Status.rb

class Status

  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :statusable, polymorphic: true

Now I'm trying to create the status Document Inside user:

* User.create!(:name =>'try',:status => {:num => '111'})
=> NameError: uninitialized constant Statu
    from /var/lib/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:230:in 'block in constantize'
    from /var/lib/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:229:in 'each'
    ....
    ....

* u = User.create!(:name =>'try')
u.status = Status.create!(:num => '222')
=> Mongoid::Errors::NoParent: 
Problem:
  Cannot persist embedded document Status without a parent document.
Summary:
  If the document is embedded, in order to be persisted it must always have a reference to its parent document. This is most likely caused by either calling Status.create or Status.create! without setting the parent document as an attribute.
Resolution:
  Ensure that you have set the parent relation if instantiating the embedded document direcly, or always create new embedded documents via the parent relation.

* u.status = {:num => '222'}
=> NameError: uninitialized constant Statu

Any idea why this happens?


Solution

  • From documentation:

    Model class name cannot end with "s", because it will be considered as the pluralized form of the word. For example Status would be considered as the plural form of Statu, which will cause a few known problems.

    So try to define your relation with the class_name metadata forcing mongoid to use that Class.

    embeds_one :status, as: :statusable, class_name: "Status"