Skip to content

Auto increment does not work correctly with embedded documents #9

@avaliani

Description

@avaliani

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions