attr_accessible(*attributes)
有什么区别& attr_protected(*attributes)
?例子会很好。
我看到许多开发人员在他们的模型中使用这些。我用谷歌搜索了差异,但我不明白它们到底是什么。在不同场景下的重要性和必要性是什么?
最佳答案
attr_accessible
( documentation ) 表示“指定的属性是可访问的,所有其他属性都受到保护”(将其视为 whitelisting 。)
然而attr_protected
( documentation ) 表示“指定的属性受到保护,所有其他属性都可以访问”(将其视为 blacklisting 。)
protected 属性是一种只能显式修改(例如通过 attribute=)并且不能通过批量赋值更新(例如使用 model.update_attributes
或通过将属性传递给 new
)的属性。尝试通过批量赋值更新 protected 属性时的行为取决于 mass_assignment_sanitizer
设置(请参阅下面的更新)。
经典的例子是如果 User
模型有一个 is_admin
属性 您可以保护该属性以防止表单提交允许将任何用户设置为管理员。
例子:
class User < ActiveRecord::Base
# explicitly protect is_admin, any new attributes added to the model
# in future will be unprotected so we need to remember to come back
# and add any other sensitive attributes here in the future
attr_protected :is_admin
end
和....相比:
class User < ActiveRecord::Base
# explicitly unprotect name and bio, any new attributes added to the model
# in the future will need to be listed here if we want them to be accessible
attr_accessible :name, :bio
end
现在,假设
is_admin
属性 protected :> u = User.find_by_name('mikej')
> u.is_admin?
false
> u.update_attributes(:name => 'new name', :is_admin => true)
> u.is_admin?
false
> u.name
"new name"
> u.is_admin = true # setting it explicitly
> u.save
> u.is_admin?
true
更新:Rails 的更高版本引入了批量分配清理器的概念,以控制尝试通过批量分配更新 protected 属性时的行为。在 Rails 3.2 及更高版本中,这可以通过设置
mass_assignment_sanitizer
来控制。在配置中。默认是只记录尝试并允许代码继续执行,但开发的标准环境配置将其设置为 :strict
在尝试更新 protected 属性时引发异常。
关于ruby-on-rails - attr_accessible(*attributes) 和 attr_protected(*attributes) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652907/