What is the difference between attr_accessible(*attributes) & attr_protected(*attributes)? Examples would be nice.
I see many developers use these in their models. I googled for the differences, but I don’t get exactly what they are. What is the importance and its necessity in different scenarios?
attr_accessible(documentation) says “the specified attributes are accessible and all others are protected” (think of it as whitelisting.)whereas
attr_protected(documentation) says “the specified attributes are protected and all others are accessible” (think of it as blacklisting.)A protected attribute is one that can only be modified explicitly (e.g. via attribute=) and can’t be updated via mass assignment (e.g. using
model.update_attributesor by passing attributes tonew). The behaviour upon an attempt to update a protected attribute via mass assignment depends on themass_assignment_sanitizersetting (see the update below).The classic example would be if a
Usermodel had anis_adminattribute you could protect that attribute to prevent form submissions that would allow any user to be set as an administrator.example:
compared with:
Now, assuming
is_adminattribute is protected:Update: Later versions of Rails introduced the concept of a mass assignment sanitizer to control the behaviour upon attempts to update protected attributes via mass assignment. In Rails 3.2 and later this can be controlled by setting
mass_assignment_sanitizerin config. The default is to just log the attempts and allow code execution to continue, but the standard environment config for development sets this to:strictwhich raises as exception on an attempt to update a protected attribute.