attr_accessible(*attributes)
和attr_accessible(*attributes)
之间有什么区别;attr_protected(*attributes)
? 举个例子就好了.
我看到许多开发人员在他们的模型中使用这些.我在谷歌上搜索差异,但我不知道它们到底是什么.在不同的场景中,它的重要性和必要性是什么?
attr_accessible(*attributes)
和attr_accessible(*attributes)
之间有什么区别;attr_protected(*attributes)
? 举个例子就好了.
我看到许多开发人员在他们的模型中使用这些.我在谷歌上搜索差异,但我不知道它们到底是什么.在不同的场景中,它的重要性和必要性是什么?
attr_accessible
(documentation)表示"指定的属性是可访问的,所有其他属性都受到保护"(将其视为whitelisting)
鉴于
attr_protected
(documentation)表示"指定的属性受到保护,所有其他属性都可以访问"(将其视为blacklisting)
protected attribute只能被明确修改(例如,通过attribute=),不能通过质量分配(例如,使用model.update_attributes
或通过将属性传递给new
)进行更新.try 通过质量分配更新受保护属性时的行为取决于mass_assignment_sanitizer
设置(请参阅下面的更新).
classic 的例子是,如果一个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
属性受到保护:
> 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的更高版本引入了a mass assignment sanitizer的概念,以控制试图通过大规模分配更新受保护属性时的行为.在Rails 3.2及更高版本中,这可以通过在配置中设置mass_assignment_sanitizer
来控制.默认情况下,只记录try 并允许代码继续执行,但标准的environment config for development将其设置为:strict
,这会在try 更新受保护属性时引发异常.