attr_accessible(* attributes)& attr_protected(*属性)?

时间:2010-04-16 12:32:16

标签: ruby-on-rails activerecord

attr_accessible(*attributes)&之间有什么区别? attr_protected(*attributes)?例子很好。

我看到许多开发人员在他们的模型中使用这些。我搜索了差异,但我不确切地知道它们是什么。在不同的情景中,重要性和必要性是什么?

2 个答案:

答案 0 :(得分:99)

attr_accessibledocumentation)说“指定的属性可以访问,所有其他属性都受到保护”(将其视为whitelisting。)

,而

attr_protecteddocumentation)说“指定的属性受到保护,其他所有属性都可以访问”(将其视为blacklisting。)

受保护属性是一个只能显式修改的属性(例如,通过 attribute = ),并且无法通过质量分配进行更新(例如使用{{1}或者通过将属性传递给model.update_attributes)。尝试通过批量分配更新受保护属性时的行为取决于new设置(请参阅下面的更新)。

经典示例是,如果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

更新:Rails的更高版本引入了质量分配清理程序的概念,以控制尝试通过批量分配更新受保护属性时的行为。在Rails 3.2及更高版本中,可以通过在config中设置> 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 来控制。默认情况下,只记录尝试并允许代码执行继续,但开发的标准环境配置将此设置为mass_assignment_sanitizer,这会在尝试更新受保护属性时引发异常。

答案 1 :(得分:7)

attr_accessible是一个用于质量分配的白名单...

class Foo < ActiveRecord::Base #has attributes foo and bar
  attr_accessible :foo
end
f = Foo.new :foo => "test", :bar => "test"
f.foo #=> "test"
f.bar #=> nil

attr_proteceted是一个用于质量分配的黑名单...

class Foo < ActiveRecord::Base #has attributes foo and bar
  attr_protected :bar
end
f = Foo.new :foo => "test", :bar => "test"
f.foo #=> "test"
f.bar #=> nil