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

Tos*_*shi 7 ruby ruby-on-rails ruby-on-rails-4 ruby-on-rails-5

使用Active Record,我们可以访问类似的值

方法访问

user = User.find(1)
user.name #=> 'John'
Run Code Online (Sandbox Code Playgroud)

要么

哈希访问

user[:name] #=> 'John'
Run Code Online (Sandbox Code Playgroud)

我只是想知道何时使用哪种,或者是否有最佳实践?我个人更喜欢method access因为我觉得这更像是红宝石.但是当我看到其他人的代码时,我会面对hash access.

And*_*eko 6

Rails约定是使用ActiveRecord :: AttributeMethods :: Read#read_attribute(点表示法),而不是它的别名ActiveRecord :: AttributeMethods#[],其中:

返回attr_name在进行类型转换后标识的属性的值(例如,“2004-12-12”在日期列中强制转换为日期对象,如Date.new(2004, 12, 12)).ActiveModel::MissingAttributeError如果缺少已标识的属性,则会引发 此问题.