We noticed that with embedded documents the before_create callback is called twice - once for the top level document and once for the embedded document. This results in two issues:
a) the sequence is no longer sequential
b) (the bigger issue) the object id of the in memory object is different from the object id of the persisted object. Meaning if you reference that object's id without reloading it you will be storing invalid references in other objects.
Example:
class Obj
include Mongoid::Document
auto_increment :_id, :collection => :obj_id_sequence, :seed => 1
embeds_one :obj_config
after_initialize do |c|
c.create_obj_config unless c.obj_config
end
end
class ObjConfig
include Mongoid::Document
embedded_in :obj
end
c1 = Obj.create!() # before_create called twice
puts c1.id
# outputs 3
Is there a way to handle this aside from not calling before_create for the embedded objects?
Thanks.
We noticed that with embedded documents the before_create callback is called twice - once for the top level document and once for the embedded document. This results in two issues:
a) the sequence is no longer sequential
b) (the bigger issue) the object id of the in memory object is different from the object id of the persisted object. Meaning if you reference that object's id without reloading it you will be storing invalid references in other objects.
Example:
Is there a way to handle this aside from not calling before_create for the embedded objects?
Thanks.