attr_accessor vs attr_accessible (Ruby on Rails)

The post describes what mean ‘attr_accessor’ and ‘attr_accessible’ in a Rails Model.

attr_accessor

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.

[codesyntax lang=”rails”]

def myvar
@myvar
end
def myvar=(myvar)
@myvar= myvar
end
def myvar
@myvar
end
def myvar=(myvar)
@myvar= myvar
end

[/codesyntax]

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.

 

attr_accessible

[codesyntax lang=”rails”]

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
..
end

[/codesyntax]

 

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

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.

3 thoughts on “attr_accessor vs attr_accessible (Ruby on Rails)”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>