mongoid/mongoid — Issue #1539: ObjectID of record changes after update
Author: nathankleyn
Created: 2011-12-31 16:51:18+00:00
State: open

In our project, we have this model called Space. This model has a field called :is_master, and only one Space at a time can have this set to true. So, in an after_save, we have the following logic to ensure that is always the case:

Space.where(:_id.ne => self.id, site_id: site.id, is_master: true).each do |true_master|
true_master.update_attributes!(is_master: false)
end

For some reason, on the latest master of Mongoid, and on 2.3.4, we experience issues with the ID changing after the update, ie. after calling `:update_attributes!` in that code above. The following is an excerpt from a Pry session, where I can reproduce the issue readily:

pry(#)> true_master._id
=> "4eff3938fb613c50d0000065"
pry(#)> true_master.is_master = false
=> false
pry(#)> true_master.save!
MONGODB platform-ruby-frontend_ci['$cmd'].find({"count"=>"spaces", "query"=>{:domain=>"Domain 10", :_id=>{"$ne"=>"4eff3938fb613c50d0000065"}}, "fields"=>nil}).limit(-1)
MONGODB platform-ruby-frontend_ci['sites'].find({:_id=>"4eff3938fb613c50d0000063"}).limit(-1).sort([[:_id, :asc]])
MONGODB platform-ruby-frontend_ci['spaces'].update({"_id"=>"4eff3972fb613c50d0000068"}, {"$set"=>{"is_master"=>false, "updated_at"=>2011-12-31 16:33:54 UTC}})
=> true
pry(#)> true_master.id
=> "4eff3972fb613c50d0000068"

As you can see, it does a .find with the original ID (which is the right one), but then for some reason the ID changes when the update is called. Of course, now calling .reload on that model, you can see that it is no longer associating properly to the persisted copy:

pry(#)> true_master.reload
MONGODB platform-ruby-frontend_ci['spaces'].find({:_id=>"4eff3972fb613c50d0000068"}).limit(-1)
Mongoid::Errors::DocumentNotFound: Document not found for class Space with id(s) 4eff3972fb613c50d0000068.
from /home/vagrant/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/bundler/gems/mongoid-19606e698126/lib/mongoid/reloading.rb:21:in `block in reload'

For confirmation:

pry(#)> true_master.id
=> "4eff3972fb613c50d0000068" # but it should be "4eff3938fb613c50d0000063"!

Please do let me know if I can provide further information about this issue; we're tearing our hair out about this one! I'll happily do a `git bisect` against Mongoid if that would help?