Rails,activerecord:self [:attribute]与self.attribute [英] Rails, activerecord: self[:attribute] vs self.attribute
问题描述
在rails中访问活动记录列/属性时,使用self [:attribute]与self.attribute有什么区别?这会影响吸气剂和吸气剂吗?
它们都是获取属性的方法-它们都是吸气剂。 self.attribtue
是一个更传统的吸气剂,而 self [:attribute]
基本上只是 []
方法。
我建议仅使用 self.attribute
方法,因为它在语法上更好但是,当其他方法覆盖 self.attribute
方法时,使用 self [:attribute]
会派上用场。 / p>
例如,假设您的用户模型的数据库列为
,因此得到 user.name
。但是,假设您安装了一个gem,为每个模型添加了 #name
方法。为了避免复杂化,一种选择是使用 user [:name]
直接访问它,而无需通过受到破坏的方法。
When accessing active record column/attributes in rails, what is the difference between using self[:attribute] vs self.attribute? Does this affect getters and setters?
They're both just methods to get to the attribute - they're both just getters. self.attribtue
is a more "traditional" getter, whereas self[:attribute]
is basically just the []
method. Switching between using either has no ramifications.
I'd recommend using only the self.attribute
method because it's syntactically nicer. However, using the self[:attribute]
can come in handy when something else overrides the self.attribute
method.
For example, suppose you have a User model with a name
database column, so you'd get user.name
. But let's say you install a gem that adds a #name
method to each of your models. To avoid the complication, one option is to use user[:name]
to access it directly without going through the compromised method.
这篇关于Rails,activerecord:self [:attribute]与self.attribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!