2

I can't find any tutorials for newbies. Aren't there any simple rules for using attr_accessible? Should I use it for attributes that users can set from forms?

What if all attributes can be set from forms?

I would appreciate a link or short advice. I already found http://asciicasts.com/episodes/26-hackers-love-mass-assignment

Martin Petrov
  • 2,633
  • 4
  • 30
  • 44

2 Answers2

5

attr_accessible is a white list of attributes that can be mass assigned to the model. It is a strategy which says you need to explicitly list all the attributes. This way the "open ports" are well known and listed in the model clearly. This is opposite of attr_protected which is a black list of fields to be protected from mass assignment.

Often in even moderate to simple application there are foreign key type fields such as user_id or company_id which may not be determined by user input. Those fields must be protected from user input. Primary key field 'id' is normally protected by Rails anyway.

If your model has all columns that can be updated by Form input, then sure go ahead a list them with attr_accessible (or you may want to skip attr_accessible for this particular model).

Don't throw the baby out with the bathwater however, attr_accessible is a good thing and ensure that you use it in other models which may not be as open as the one you are talking about in the your question.

I generally use attr_protected on models with a large number of columns and attr_accessible on most others.

Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
Aditya Sanghi
  • 13,370
  • 2
  • 44
  • 50
  • Thank you. I think it's clear now. I'm going to use attr_accessible always, even if all columns can be updated by Form input, because foreign key type fields should be protected. – Martin Petrov Dec 27 '10 at 13:19
2

Check this out: Use attr_protected or we will hack you

fantactuka
  • 3,298
  • 19
  • 29
  • OK, as long as I understood attr_protected/attr_accessible is used for attributes you don't want anybody to change. These are the attributes that are not available for users to set in forms. Also, hackers can change relationships between models, if certain attributes are not protected. It's best to do it with attr_accessible. – Martin Petrov Dec 27 '10 at 13:06