Difference Between attr_accessor and attr_accessible

Hello everyone,

I am working on a Rails toutorial and was wondering what the difference
Between attr_accessor and attr_accessible.

The tutorial is explaining how to create a secure password
authintication system and passed :password into the attr_accessor
function and said it was because it needed it to be virtual and not a
row in the database. It then also passes :password as well as
:password_confirmation to attr_accessible.

I was wondering why it needed to pass them to attr_accessible as well.

Thank you for your help

Exert from tutorial:

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

Automatically create the virtual attribute ‘password_confirmation’.

validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6…40 }
end

attr_accessor :password

is a shortcut for defining:

def password
@password
end

def password=(val)
@password = val
end

…which allows you to get and set the variable @password. Rails defines
those methods automatically for all database columns. What do you do if
you don’t want users to be able set a particular database column?

That makes since. So attr_accsesible is a white list of mass assignable
variables that are actual columns in the database. But if I am not
mistaken I can always access variables via somerecordclass.variable =
value right? So what does one gain from prohibiting mass assignment.

This also brings up another question to me is

someactiverecord.update_attributes :only_one_attr => “only_one_value”

considered mass assignment

Thank you everyone

Tyrel R. wrote in post #1008865:

That makes since. So attr_accsesible is a white list of mass assignable
variables that are actual columns in the database.

I don’t believe that is correct. I think attr_accessible is a white
list of all of your model’s instance variables, whether they were
defined automatically by rails because they were columns in your
database, or they were defined manually by you. Hence, the “virtual
column” language for the instance variables you define yourself.

But if I am not
mistaken I can always access variables via somerecordclass.variable =
value right?

somerecordclass.variable would be a ‘class instance variable’, which is
different from an instance variable. An instance variable belongs to an
object (or instance) of a class. A class instance variable belongs to
the class object.

So what does one gain from prohibiting mass assignment.

It prevents people from changing things you don’t want changed.

This also brings up another question to me is

someactiverecord.update_attributes :only_one_attr => “only_one_value”

Are you under the impression that this is a rails forum?