简体   繁体   中英

How do you use attr_accessible?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM