Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto increment does not work correctly with embedded documents #9

Open
avaliani opened this issue Aug 13, 2014 · 0 comments
Open

Auto increment does not work correctly with embedded documents #9

avaliani opened this issue Aug 13, 2014 · 0 comments

Comments

@avaliani
Copy link

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.

@proton proton added the bug label Aug 18, 2014
@proton proton self-assigned this Aug 18, 2014
@proton proton removed their assignment Oct 28, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants