I just had a general question about Ruby on Rails and the attr_accessible attributes that go in the models (Rails 3). Can someone explain which model attributes are supposed to be defined there? I remember something about risk for mass assignment, though I'm not too knowledgeable in this aspect... Thanks :)
Imagine an order class with some fields:
Order.new({ :type => 'Corn', :quantity => 6 })
Now imagine that the order also has a discount code, say :price_off. You wouldn't want to tag :price_off as attr_accessible. This stops malicious code from being able to craft a post that ends up doing something 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. A crafted POST could still set it.
Using attr_accessible white lists those things are can be mass assigned and protects fields that you want explicit control of in your code.
Difference between attr_accessor and attr_accessible has some additional links.
attr_accessible allows you to define a whitelist of attributes on the model that can be mass assigned. So if you have 10 attrs but only whitelist 3 of them, only those three can be mass assigned.
class Foo < ActiveRecord:Base
#lets say you have attrs one, two, three
attr_accessible :one, :two
end
#You can do this:
Foo.new({:one => 1, :two => 2})
#if you were to do this:
Foo.new({:one => 1, :two => 2, :three => 3})
#Foo's three attr would not be set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With