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
Best Answer
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)
orupdate_attributes(attrs)
.Here's a mass assignment:
You can imagine that the order might also have a discount code, say
:price_off
. If you don't tag:price_off
asattr_accessible
you stop malicious code from being able to do like so: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. Usingattr_accessible
white lists those things that can be mass assigned.