ActiveRecord 访问器点 (.) 与方括号 ([])

ActiveRecord accessor dot(.) vs bracket([])

使用 Active Record,我们可以访问像

这样的值

方法访问

user = User.find(1)
user.name #=> 'John'

哈希访问

user[:name] #=> 'John'

我只是想知道什么时候使用哪个,或者有什么最佳实践吗? 我个人更喜欢 method access,因为我觉得那更像是 ruby 方式。然而,当我看到别人的代码时,我面对 hash access.

Rails约定是使用ActiveRecord::AttributeMethods::Read#read_attribute (dot notation), rather than its alias ActiveRecord::AttributeMethods#[],即:

Returns the value of the attribute identified by attr_name after it has been typecast (for example, “2004-12-12” in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises ActiveModel::MissingAttributeError if the identified attribute is missing.

我强烈建议不要使用括号表示法,因为它会破坏方法调用的继承层次结构并使重构更加困难。

如果我的模型有一个属性 name,并且我决定每次有人阅读它时我都想增强这个名字,一个非常惯用的方法是:

def name "Awesome #{super}!" end

我的应用程序中任何使用方法版本的地方都可以正常工作,任何使用 [] 符号的地方都可以 return 原始数据库数据。我可以覆盖 [] 但随后我将需要检查特定属性的特殊条件。整件事将是一场噩梦。

另一种情况,假设我有一个过去存储在数据库中的属性,但过了一段时间后决定应该即时计算它,并最终删除了数据库列。使用方法版本,我需要做的就是将方法添加到我的模型中。使用 [] 表示法,过程会困难得多。

另外 [] 提供了一个微不足道的性能改进,所以虽然它看起来像原始数据 "closer" 但实际上不是。