Attr_accessor_with_default -- how to use?

I have the following model:

class User < ActiveRecord::Base

devise
:registerable, :database_authenticatable, :recoverable, :confirmable,
:rememberable, :trackable, :validatable
attr_accessor_with_default :role, ‘user’

attr_accessible :email, :password, :password_confirmation, :first_name,
:last_name, :company_name, :phone, :role
end

Role is a column in my database (I’m beginning to wonder if my
troubles start there.)

Here’s a playback of an irb session on this model:

u = User.new
=> #<User id: nil, email: “”, encrypted_password: “”, password_salt:
“”, confirmation_token: nil, confirmed_at: nil, confirmation_sent_at:
nil, reset_password_token: nil, remember_token: nil,
remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil,
last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil,
created_at: nil, updated_at: nil, first_name: nil, last_name: nil,
company_name: nil, phone: nil, role: nil>

u.email = ‘[email protected]
=> “[email protected]

u.password = u.password_confirmation = ‘abc123’
=> “abc123”

u.role
=> “user”

So far, so good, I’m getting a default value here. Next, we assign a
different value.

u.role = ‘admin’
=> “admin”

u.save!
=> true

Okay, looks good. Try an immediate check to see what the value is:

u.role
=> “admin”

Now let’s find it again from scratch, to reload what the database
believes is true:

u = User.find_by_email(‘[email protected]’)
=> #<User id: 6, email: “[email protected]”, encrypted_password:
“1971f891cd2e83ef0d2fe9ba31b548cb2740573d”, password_salt:
“ENAl9O1NDurotmGjeBJT”, confirmation_token: “SEHEmHUYtmaeaeHPLq4y”,
confirmed_at: nil, confirmation_sent_at: “2010-09-18 14:05:26”,
reset_password_token: nil, remember_token: nil, remember_created_at:
nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil,
current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: “2010-09-18
14:05:26”, updated_at: “2010-09-18 14:05:26”, first_name: nil,
last_name: nil, company_name: nil, phone: nil, role: nil>

And we are at this point, where I ask WTF??

u.role
=> “user”

Do I have a fundamental misunderstanding of this feature? Should I be
setting my default in the database instead, since it’s a column? What
do you use an attr_accessor for, let alone one with a handy default
value?

Thanks in advance,

Walter

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs