gpt4 book ai didi

ruby-on-rails - ActiveRecord 访问器点 (.) 与方括号 ([])

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:20 26 4
gpt4 key购买 nike

使用 Active Record,我们可以访问像这样的值

方法访问

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

哈希访问

user[:name] #=> 'John'

我只是想知道什么时候使用哪个,或者有什么最佳实践吗?我个人更喜欢 method access 因为我觉得这更像是 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.

关于ruby-on-rails - ActiveRecord 访问器点 (.) 与方括号 ([]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com