加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – ActiveRecord访问器点(.)与支架([])

发布时间:2020-12-17 03:25:09 所属栏目:百科 来源:网络整理
导读:使用Active Record,我们可以访问类似的值 方法访问 user = User.find(1)user.name #= 'John' 要么 哈希访问 user[:name] #= 'John' 我只是想知道何时使用哪种,或者是否有最佳实践? 我个人更喜欢方法访问,因为我觉得这更像是ruby方式.但是,当我看到其他人的
使用Active Record,我们可以访问类似的值

方法访问

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

要么

哈希访问

user[:name] #=> 'John'

我只是想知道何时使用哪种,或者是否有最佳实践?
我个人更喜欢方法访问,因为我觉得这更像是ruby方式.但是,当我看到其他人的代码时,我面临着哈希访问.

解决方法

Rails惯例是使用 ActiveRecord::AttributeMethods::Read#read_attribute(点表示法),而不是别名 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读