Rails 模型类中的 attr_accessor 和 attr_accessible 让我有点头疼

tiseheaini · March 06, 2012 · Last by congteng replied at March 06, 2012 · 5712 hits

还读了很多代码。在 ruby-china 的源码中看到了 attr_accessor 和 attr_accessible,上网找资料看了看,似乎有点明白了,也有点不明白。 我只想知道怎么在模型类里自己写校验的时候如何用表单了诸如 :eamil :password :address 字段的数据。 我翻了翻《Web 开发敏捷之道》,里面好像没讲这方面的内容。

@tiseheaini 你需要弄清楚attr_accessor, attr_accessible, attr_protected这三者的区别。 提醒一下,attr_accessor是 Ruby 提供的方法,它和 Rails 没关系,后面两个则是 Rails 提供的方法。

前面两个名字确实比较混。。

http://jhjguxin.sinaapp.com/2012/03/06/mass-assignment-vulnerability-how-to-force-dev-define-attr_accesible-by-homakov/ attr_accessible(*args) Specifies a white list of model attributes that can be set via mass-assignment.指定一个 model 属性的白名单,其可以通过来定制(白名单里面的的值)。

Like attr_protected, a role for the attributes is optional, if no role is provided then :default is used. A role can be defined by using the :as option.

如同 attr_protected,添加的 attributes 是他的一个选项,如果没有角色被提供,那么会使用:default 选项。一个属性 role 可以在定义的时候使用:as 选项(定制别名)

This is the opposite of the attr_protected macro: Mass-assignment will only set attributes in this list, to assign to the rest of attributes you can use direct writer methods. This is meant to protect sensitive attributes from being overwritten by malicious users tampering with URLs or forms. If you’d rather start from an all-open default and restrict attributes as needed, have a look at attr_protected.

这是 attr_protected macro(宏)的相反操作:Mass-assignment 将会仅仅只能设定在这个名单中的 attributes,要分派其余的属性的值你可以使用直接的写方法(赋值然后 save)。这里意图去保护敏感的 attributes 防止其被恶意的用户重写或篡改通过 forms 的 URLs。如果你宁愿开始一个默认全部开放以及需要限制某些属性,去看一看 attr_protected.

最近关于这个讨论还真不少

You need to Sign in before reply, if you don't have an account, please Sign up first.