Skip to content

Instantly share code, notes, and snippets.

@Koronen
Last active August 29, 2015 14:04
Show Gist options
  • Save Koronen/474eceec27ed6adeb29c to your computer and use it in GitHub Desktop.
Save Koronen/474eceec27ed6adeb29c to your computer and use it in GitHub Desktop.
Mongoid 3.1.6 update_attributes gotcha
[1] pry(main)> p=Post.create
=> #<Post _id: 53db80397526a46c23000001, >
[2] pry(main)> p.title="foo"
NoMethodError: undefined method `title=' for #<Post _id: 53db80397526a46c23000001, >
from /home/koronen/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/mongoid-3.1.6/lib/mongoid/attributes.rb:320:in `method_missing'
[3] pry(main)> p.update_attributes(title: 'a')
=> true
[4] pry(main)> Post.first
=> #<Post _id: 53db80397526a46c23000001, title: "a">
[5] pry(main)> _.title
=> "a"
irb(main):001:0> p=Post.create
=> #<Post _id: 53db86927061723c9b000000, >
irb(main):002:0> p.update_attributes(title: 'foo')
Mongoid::Errors::UnknownAttribute:
Problem:
Attempted to set a value for 'title' which is not allowed on the model Post.
Summary:
Without including Mongoid::Attributes::Dynamic in your model and the attribute does not already exist in the attributes hash, attempting to call Post#title= for it is not allowed. This is also triggered by passing the attribute to any method that accepts an attributes hash, and is raised instead of getting a NoMethodError.
Resolution:
You can include Mongoid::Attributes::Dynamic if you expect to be writing values for undefined fields often.
gem 'mongoid', '3.1.6'
# app/models/post.rb
class Post
include Mongoid::Document
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment