Last active
August 29, 2015 14:04
-
-
Save Koronen/474eceec27ed6adeb29c to your computer and use it in GitHub Desktop.
Mongoid 3.1.6 update_attributes gotcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem 'mongoid', '3.1.6' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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