Mongoid unstable associations

Consider the following:

class Parent
  include Mongoid::Document
  field:name
  references_one :child

  before_create :initialize_child

  protected

  def initialize_child
    self.child = Child.create
  end

end

class Child
  include Mongoid::Document
  field:name
  referenced_in :parent
end

In the console, I get the following weird behavior:

> p = Parent.create
 => #<Parent _id: 4d811748fc15ea355d00000b, name: nil> 
> p.child
 => #<Child _id: 4d811748fc15ea355d00000c, name: nil, parent_id: BSON::ObjectId('4d811748fc15ea355d00000b')> 

All still. Now when I try to get a parent and then find a child - no luck ...

> p = Parent.last
 => #<Parent _id: 4d811748fc15ea355d00000b, name: nil> 
> p.child
 => nil 

This happens to me with both mongoid rc6 and rc7

Am I doing something wrong (I'm new to mongoid) or is this a mistake? Any work around?

Thank!!

Jonathan

+3
source share
1 answer

Since the baby is not built-in, it will not automatically save it on its own

Try

class Parent
  include Mongoid::Document
  field:name
  references_one :child, autosave: true 

  before_create :initialize_child

  protected
  def initialize_child
    self.child ||= Child.new
  end
end

In addition, you can expect the child to be embedded in the parent document. If so, you need to switch to "embedded_in"

+4
source

All Articles