Question

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

Was it helpful?

Solution

You've got a couple of concepts mixed together here, so I'll try to untangle them.

attr_accessor is for setting up a readable and writable attribute. It is the equivalent of saying attr_reader and attr_writer. Since your question isn't directly about attr_accessor, I won't address it anymore than saying check out this link on Accessors.


According to the Rails docs: attr_accessible is the opposite of the attr_protected macro

You're correct that these methods are used to prevent Mass Assignment vulnerabilities.

  • attr_accessible says which attributes can be set by mass assignment.
  • attr_protected says 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:

config.active_record.whitelist_attributes = true

In that case you'd use attr_accessible frequently.

And attr_protected? If you went the opposite way and said false on whitelisting attributes, how would you declare which attributes shouldn't be mass assignable? If you said attr_protected you're right! :D

Typically you'd want to set fields like :admin as attr_protected because 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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top