Rails 批量分配定义和 attr_accessible 使用
只是想清楚什么是批量分配以及如何围绕它进行编码。是批量分配使用散列对许多字段进行分配,即......
@user = User.new(params[:user])
并且为了防止这种情况,您使用attr_accessible,例如:
attr_accessible :name, :email
这样就无法添加像 :admin 这样的字段通过批量分配?
但是我们可以在代码中修改它,例如:
@user.admin = true
那么,如果我们没有 attr_accessible 那么所有内容都可以进行批量分配,这是真的吗?
最后是棘手的一点……即使有一个像“attr_accessible :name”这样的attr_accessible,是否也意味着所有其他字段现在不 > 可以进行批量分配吗?
Just want to be clear on what mass assignment is and how to code around it. Is mass assignment the assignment of many fields using a hash, ie like..
@user = User.new(params[:user])
And to prevent this you use attr_accessible like:
attr_accessible :name, :email
So that a field like :admin could not be added by mass assignment?
But we can modify it in code by something like:
@user.admin = true
So is it true that if we don't have attr_accessible then everything is accessible for mass assignment?
And finally the tricky point ... is it true that even with one attr_accessible like "attr_accessible :name" means that all other fields are now not accessible for mass assignment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你所有的假设都是正确的。如果没有 attr_accessible,所有字段都可以批量分配。如果您开始使用 attr_accessible,则只有您指定的字段可以批量分配。
All of your assumptions are correct. Without attr_accessible, all fields are open to mass assignment. If you start using attr_accessible, only the fields you specify are open to mass assignment.
正如 Srdjan 所指出的,您的所有假设都是正确的。正如您所知,还有一个与 attr_accessible 相反的 attr_protected 方法。
换句话说,
将阻止 :admin 被批量分配,但将允许所有其他字段。
As pointed out by Srdjan all of your assumptions are correct. Just so you know, there is also an attr_protected method which is the opposite of attr_accessible.
In other words
will prevent :admin from being mass-assigned but will allow all other fields.
假设您的 config/application.rb 中的 config.active_record.whitelist_attributes 设置为 false,Srdjan 的答案是正确的。
如果设置为
true
,则所有属性都将默认情况下免受批量分配,除非attr_accessible
或attr_protected
用过的。Srdjan's answer is correct assuming that
config.active_record.whitelist_attributes
is set tofalse
in yourconfig/application.rb
.If it is set to
true
, all attributes will be protected from mass assignment by default unlessattr_accessible
orattr_protected
is used.