I’m doing my first steps in Rails and in object-oriented programming.
There is something quite fudemental that I would like to understand: why do we need attr_accessible within the model?
I have read that hackers can use mass-assignment in order to change database entries and therefore compremise security, and that’s why sensitive fields need protection (using atribute_protected in this case).
Is attr_accessible the opposite of atribute_protected? If so, why do we need to state which fields are accessible and which are not? aren’t those fields accessible by defult? And what is attr_accessor used for?
I noticed that if I don’t make some fields acessible, my application doesn’t run. Can I use attr_acessible for sensitive fields like :password_digest and :admin?
It would be amazing if someone could explain it to me.
All the best,
TimmyOnRails
You’ve got a couple of concepts mixed together here, so I’ll try to untangle them.
attr_accessoris for setting up a readable and writable attribute. It is the equivalent of sayingattr_readerandattr_writer. Since your question isn’t directly aboutattr_accessor, I won’t address it anymore than saying check out this link on Accessors.According to the Rails docs:
attr_accessibleis the opposite of the attr_protected macroYou’re correct that these methods are used to prevent Mass Assignment vulnerabilities.
attr_accessiblesays which attributes can be set by mass assignment.attr_protectedsays which attributes cannot be set by mass assignment.So what’s the use case for each? In one case you’re able to set a global config option that makes it so that all attributes must be declared
attr_accessible:In that case you’d use
attr_accessiblefrequently.And
attr_protected? If you went the opposite way and saidfalseon whitelisting attributes, how would you declare which attributes shouldn’t be mass assignable? If you saidattr_protectedyou’re right! 😀Typically you’d want to set fields like
:adminasattr_protectedbecause you don’t want an attacker coming in and escalating their privileges to an admin role.Mass assignment is not something that’s easy to get right. Big, smart development teams have gotten this wrong. So tred carefully and make sure you understand what’s going on!