Using attr_accessor in Rails model classes
- Don’t confuse
attr_accessor
andattr_accessible
– they have very similar names attr_accessor
is a pure Ruby function to create reader and writer methods for an instance variableattr_accessible
is a pre-Rails 4 function to list the model attributes (e.g., database fields) that can be set via mass assignment, providing access control
You can use attr_accessor
on a Rails model to create non-persisted instance variables. For example:
class Stock
attr_accessor :current_price
end
This allows you to get the @current_price
of a stock – something that would make no sense to persist.