Ruby on Rails attr_accessor – Why Is attr_accessor Necessary in Rails?

rubyruby-on-rails

I occasionally see attribute accessors/readers/writers in the code for models. Are these necessary if I want to be able to update attributes from the view / controller code?

I am a beginner so I am really talking about basic applications.

Best Answer

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.