How do you use attr_accessible?

前端 未结 2 1176
陌清茗
陌清茗 2021-01-14 19:32

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

相关标签:
2条回答
  • 2021-01-14 20:04

    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.

    0 讨论(0)
  • 2021-01-14 20:17

    Check this out: Use attr_protected or we will hack you

    0 讨论(0)
提交回复
热议问题