attr_accessor vs attr_accessible (Ruby on Rails)
The post describes what mean ‘attr_accessor’ and ‘attr_accessible’ in a Rails Model.
It creates a pair of accessor methods for an instance variable. you can think or attr_accessor as a ruby method that is the combination of attr_reader and attr_writer
attr_accessor is an easy way to create read and write accessors in your class.
attr_accessor :myvar replaces the following.
def myvar @myvar end def myvar=(myvar) @myvar= myvar end def myvar @myvar end def myvar=(myvar) @myvar= myvar end
NOTE! Don’t use attr_accessor for database attributes – Rails creates those accessors for you.
attr_accessor is used when you do not have a column in your database, but still want to show a field in your forms. This field is a “virtual attribute” in a Rails model.
virtual attribute – an attribute not corresponding to a column in the database.
class User < ActiveRecord::Base attr_accessible :name, :email, :password, :password_confirmation .. end
attr_accessible is used to identify attributes that are accessible by your controller methods.
attr_accessible will only allow access to the attributes that you specify, denying the rest.
attr_accessible makes a property available for mass-assignment.
attr_protected will deny access to the attributes that you specify, allowing the rest, and specifying neither in your model will allow access to all attributes.
attr_protected is the opposite of attr_accessible which means the field that I do NOT want anyone to be allowed to Mass Assign to.