views:

91

answers:

3

Hi,

In RoR, what is the difference between attr_accessor and attr_accessible. From my understanding, using attr_accessor is used to create getter and setter methods for that variable, so that we can access the variable like

`Object.variable`   or    `Object.variable = some_value`

I read that attr_accessible makes that specific variable accessible to the outside world. Can someone please tell me whats the difference

+1  A: 

OK. I understand now. I read it here.

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001796

Felix
+5  A: 

attr_accessor is a ruby method that makes a getter and a setter. attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or up update_attributes(attrs).

Here's a mass assignment:

Order.new({ :type => 'Corn', :quantity => 6 })

You can imagine that the order might also have a discount code, say :price_off. If you don't tag :price_off as attr_accessible you stop malicious code from being able to do like so:

Order.new({ :type => 'Corn', :quantity => 6, :price_off => 30 })

Even if your form doesn't have a field for :price_off, if it's just in your model by default it's available so a crafted POST could still set it. Using attr_accessible white lists those things are can be mass assigned.

Paul Rubel
A: 

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.

Joshua Cheek
You have a typo, after the code block it should say `attr_accesible`
Chubas