1

I am working on dynamic form generator. And I've noticed strange behaviour

class Model
  include Mongoid::Document
  field :name, :type => String
end

model = Model.new
model.name = "My Name"
model.surname = "My Surname"
#=> NoMethodError: undefined method `surname='

but

model = Model.new( :name => "My Name", :surname => "My Surname" )
#=> ok
model.surname
#=> "My Surname"
model.surname = "New Surname"
#=> "New Surname"

Can somebody explain why I can create new fields with mass assignment and can't add fields through attribute?

1 Answer 1

3

Per the Mongoid documentation, the getter/setter methods (e.g. .surname) will only work if the field exists in the document (which is why when you create a new Model with the field, it works).

You can still set/read the fields like so:

model[:surname]
model.read_attribute(:surname)
model[:surname] = "My Surname"
model.write_attribute(:surname, "My Surname")

See http://mongoid.org/docs/documents/dynamic.html

Sign up to request clarification or add additional context in comments.

2 Comments

that is the same functionality: model[:surname] = "My Surname" and model.write_attribute(:surname, "My Surname"). What is the difference? I've just tested - looks pretty same, but there is no comments in that docs article
The source code has alias :[] :read_attribute, so they are exactly the same (same with []= and write_attribute). Just use the one you prefer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.