attr_accessor
is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to
class MyModel
def my_variable
@my_variable
end
def my_variable=(value)
@my_variable = value
end
end
attr_accessible
is a Rails method that determines what variables can be set in a mass assignment. For example, when you submit a form, and you have something like MyModel.new params[:my_model]
then you want to have a little bit more control, so that people can't submit things that you don't want them to. For example, you might do attr_accessible :email
so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email , :salary
because then a person could set their salary through a form submission. In other words, they could hack their way to a raise, costing your company real money. That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.
So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.