Using attr_accessor in Rails model classes
- Don’t confuse
attr_accessorandattr_accessible– they have very similar names attr_accessoris a pure Ruby function to create reader and writer methods for an instance variableattr_accessibleis 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
endThis allows you to get the @current_price of a stock – something that would make no sense to persist.