JCDenton
JCDenton

Reputation: 151

Unable to assign value to an ActiveModel attribute (rails 4.2)

I have created a simple users model in rails 4.2. However I am unable to assign any attribute values in the rails console

2.1.5 :001 > u = User.new
=> #<User id: nil, name: nil, email: nil, auth_token: nil, created_at: nil, updated_at: nil, enabled: true>
2.1.5 :002 > u.name = 'sample'
=> "sample"
2.1.5 :003 > u.changed
=> []
2.1.5 :004 > u
=> #<User id: nil, name: nil, email: nil, auth_token: nil, created_at: nil, updated_at: nil, enabled: true>

As you can see despite setting name the value has not changed.

Here is the model file

class User < ActiveRecord::Base
  self.primary_key = :id

  include Tokenable
  include Creatable
  include Updatable

  attr_accessor :name, :email, :auth_token, :created_at, :updated_at, :enabled
end

I know that this works fine in rails 3.2

Upvotes: 1

Views: 622

Answers (2)

max
max

Reputation: 102213

One of the biggest "selling points" of ActiveRecord is that it automatically creates setters and getters in your models based on the DB schema.

These are not just your average accessors created by attr_accessor (which is plain Ruby), they cast values to the correct type and do dirty tracking among other things.

When you use attr_accessor you´re generating setters and getters that clobber those created by ActiveRecord - which means that AR will not track changes or persist the attributes.

This is what you really want:

class User < ActiveRecord::Base
  include Tokenable
  include Creatable
  include Updatable
end

Only use attr_accessor in models when you need setters and getters for non-persisted ("virtual") attributes.

Upvotes: 2

John Baker
John Baker

Reputation: 2398

You need to save the record after assigning the new value. You can achieve that by calling update_attribute! or save! on your object. In your case:

u.name = "sample"
u.save!

or

u.update_attribute("name", "sample")

Note that update_attribute updates a single attribute and saves the record without going through the normal validation procedure

Upvotes: 0

Related Questions