Skip to content

Instantly share code, notes, and snippets.

@mtkd
Created April 23, 2011 10:23
Show Gist options
  • Save mtkd/938527 to your computer and use it in GitHub Desktop.
Save mtkd/938527 to your computer and use it in GitHub Desktop.
Mongoid ID issue with state_machine
# tl;dr if state_machine is in the model when a record is created, there is a record in Mongo, but you can't do a find() on it
# If state_machine is in the model when the record is created:
ruby-1.9.2-p0 > Upload.first.id
=> BSON::ObjectId('4db2a774c4054453d000000c')
ruby-1.9.2-p0 > BSON::ObjectId.from_string('4db2a774c4054453d000000c')
=> BSON::ObjectId('4db2a774c4054453d000000c')
ruby-1.9.2-p0 > Upload.first.id == BSON::ObjectId.from_string('4db2a774c4054453d000000c')
=> true
ruby-1.9.2-p0 > Upload.find(BSON::ObjectId.from_string('4db2a774c4054453d000000c'))
Mongoid::Errors::DocumentNotFound: Document not found for class Upload with id(s) 4db2a774c4054453d000000c.
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/bundler/gems/mongoid-e1c8a436a70b/lib/mongoid/criterion/inclusion.rb:192:in `block in execute_or_raise'
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/bundler/gems/mongoid-e1c8a436a70b/lib/mongoid/criterion/inclusion.rb:190:in `tap'
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/bundler/gems/mongoid-e1c8a436a70b/lib/mongoid/criterion/inclusion.rb:190:in `execute_or_raise'
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/bundler/gems/mongoid-e1c8a436a70b/lib/mongoid/criterion/inclusion.rb:106:in `find'
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/bundler/gems/mongoid-e1c8a436a70b/lib/mongoid/finders.rb:67:in `find'
from (irb):22
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.6/lib/rails/commands/console.rb:44:in `start'
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.6/lib/rails/commands/console.rb:8:in `start'
from /Users/mtkd/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.6/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
# if no state_machine is in the model when the record is created:
ruby-1.9.2-p0 > Upload.last.id
=> BSON::ObjectId('4db2a947c405445403000002')
ruby-1.9.2-p0 > Upload.find('4db2a947c405445403000002')
=> #<Upload _id: 4db2a947c405445403000002, _type: nil, package_filename: "file.xml", attachable_id: nil, attachable_type: nil, created_at: 2011-04-23 10:26:15 UTC>
# the only difference is this code in the model:
state_machine :state, :initial => :empty do
end
@mtkd
Copy link
Author

mtkd commented Apr 23, 2011

Awesome response - I was going to file it as a bug report but thought I was try to solve first.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment