为什么在 Rails 中需要 attr_accessor? [英] Why is attr_accessor necessary in Rails?
问题描述
我偶尔会在模型的代码中看到属性访问器/读取器/写入器.如果我希望能够从视图/控制器代码更新属性,这些是否有必要?
I occasionally see attribute accessors/readers/writers in the code for models. Are these necessary if I want to be able to update attributes from the view / controller code?
我是初学者,所以我说的是基本应用.
I am a beginner so I am really talking about basic applications.
推荐答案
attr_accessor
是 Ruby 的核心特性,用于通过 getter 和 setter 方法生成实例变量.在基本的 Ruby 中从不需要使用它(这很方便).
attr_accessor
is a core feature of Ruby and is used to generate instance variables with getter and setter methods. Its use is never required in basic Ruby (it's a convenience).
对于 ActiveRecord 模型,ActiveRecord 已经为您的数据列生成了 getter 和 setter.attr_accessor
不需要或不需要.
In the case of ActiveRecord models, getters and setters are already generated by ActiveRecord for your data columns. attr_accessor
is not needed or desirable.
如果您有其他不需要保留的实例数据(即它不是数据库列),那么您可以使用 attr_accessor
为自己节省几行代码.
If you have additional instance data you don't need to persist (i.e. it's not a database column), you could then use attr_accessor
to save yourself a few lines of code.
同名的 attr_accessible
— 在 Rails 代码中经常看到并与 attr_accessor
混淆 — 是一种在 ActiveRecord 模型中控制质量分配的弃用方法.Rails 4 不支持开箱即用;它已被强参数取代,可实现更精细的控制.
The similarly-named attr_accessible
— which is frequently seen in Rails code and confused with attr_accessor
— is a deprecated method of controlling mass assignment within ActiveRecord models. Rails 4 doesn't support it out of the box; it has been replaced by Strong Parameters, which allows more granular control.
这篇关于为什么在 Rails 中需要 attr_accessor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!