If you declare an attr_accessor then you can use it as a virtual attribute, which is basically an attribute on the model that isn’t persisted to the database.

Example case: you declare attr_accessor :password in your User model so that you can use it as a field in a new user form. When you receive their password in the corresponding create action, you can derive a hashed_password, persist it to the database, and discard the given password (which is done automatically at the end of the request).

attr_accessor is a core feature of Ruby and is used to generate instance variables with getter and setter methods. Its use is never required in basic Ruby (it’s a convenience).

In the case of ActiveRecord models, getters and setters are already generated by ActiveRecord for your data columns. attr_accessor is not needed or desirable.

If you have additional instance data you don’t need to persist (i.e. it’s not a database column), you could then use attr_accessor to save yourself a few lines of code.

The similarly-named attr_accessible — which is frequently seen in Rails code and confused with attr_accessor — is a deprecated method of controlling mass assignment within ActiveRecord models. Rails 4 doesn’t support it out of the box; it has been replaced by Strong Parameters, which allows more granular control.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s