fl00r
fl00r

Reputation: 83680

Mongoid fields issue

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?

Upvotes: 1

Views: 556

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124469

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

Upvotes: 3

Related Questions