Mongoid not persisting 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 a 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 good so far. Now when I try to fetch the parent, and then find the child -- no luck ...
> p = Parent.last
=> #<Parent _id: 4d811748fc15ea355d00000b, name: nil>
> p.child
=> nil
This happens for me with both mongoid rc6 and rc7
Am I doing something wrong (I am new to mongoid) or this a bug? Any work arounds?
Thanks!!
Jonathan
Since the child isn't embedded, it won't auto-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
Also -- you may be expected the Child to be embedded in the Parent document. If so, you'll want to switch to "embedded_in"
精彩评论