Difference between attr_accessor and attr_accessible
ruby, ruby-on-rails
Solution
`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 `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 in your model it's available by default. This means a crafted POST could still set it. Using `attr_accessible` white lists those things that can be mass assigned.
Problem
In Rails, 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