简体   繁体   English

您如何使用attr_accessible?

[英]How do you use attr_accessible?

I can't find any tutorials for newbies. 我找不到新手教程。 Aren't there any simple rules for using attr_accessible? 使用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 我已经找到了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. attr_accessible是可以批量分配给模型的属性白名单。 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. 这与attr_protected相反,attr_protected是要防止进行批量分配的字段黑名单。

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. 甚至在中等到简单的应用程序中,通常都有外键类型字段,例如user_id或company_id,这些字段可能无法由用户输入确定。 Those fields must be protected from user input. 必须保护这些字段不受用户输入。 Primary key field 'id' is normally protected by Rails anyway. 无论如何,主键字段“ id”通常都受Rails保护。

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). 如果您的模型具有可以通过“表单”输入更新的所有列,那么请确保将其列为attr_accessible(或者对于该特定模型,您可能希望跳过attr_accessible)。

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. 但是,不要将婴儿与洗澡水一起扔出去,attr_accessible是一件好事,并确保您在其他模型中使用它,而这些模型可能不像您在问题中所谈论的那样开放。

I generally use attr_protected on models with a large number of columns and attr_accessible on most others. 通常在具有大量列的模型上使用attr_protected,而在其他大多数模型上使用attr_accessible。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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