在 Ruby/Rails 模型/控制器中引用关联/属性时 *、self.* 和 @* 之间的差异 [英] Differences between *, self.* and @* when referencing associations/attributes in Ruby/Rails Models/Controllers
问题描述
假设 Rails 模型具有持久性/非持久性属性,引用它们的最佳实践是什么?如果您查看公开可用的代码,则会使用不同的模式.
Assuming a Rails Model with persistent / non-persistent attributes, what is the best practice regarding referencing them? If you look at code publicly available, different patterns are used.
例如,如果您有从一个模型到另一个模型的关联.使用 self.association_name 和 @association_name 有什么区别?.什么是更可取的方法?
For instance, if you have an association from one model to another. What is the difference between using self.association_name and @association_name?. What is the preferable way?
与在模型中使用 attr_accessor :attr 定义的非持久属性相同.您可以使用 self.attr 和 @attr 这两种方法来引用它们.什么是更可取的方法?
Same as with non-persistent attributes defined with attr_accessor :attr in Models. You can reference them with both approaches, self.attr and @attr. What is the preferable way?
推荐答案
self.x
/self.x=y
are alwaysem> 方法调用.
self.x
/self.x=y
are always method calls.
(self.x
只是 self.__send__(:x)
的糖,而 self.x = y
只是糖self.__send__(:x=, y)
)
(self.x
is just sugar for self.__send__(:x)
and self.x = y
is really just sugar for self.__send__(:x=, y)
)
@x
,另一方面,仅指一个实例变量.
@x
, on the other hand, only refers to an instance variable.
使用 @x
将不能用于 AR 关联,因为 AR 只定义了 x/x=
(它们是方法em>) 因为它的神奇操作.(AR 本质上只是通过这些方法捕获"意图访问,并通过它自己的内部数据结构路由,这些数据结构与任何类似命名的实例变量无关.)
Using @x
will not work with AR associations as AR only defines x/x=
(which are methods) for its magical operation. (AR essentially just "captures" intent access through these methods and routes through its own internal data structures which are unrelated to any similar-named instance variables.)
attr_accessor
允许双向访问" 因为且仅仅因为它使用同名的实例变量作为它的支持(它必须将值存储在某处).考虑 attr_accessor :x
等价于:
attr_accessor
allows "accessing both ways" because and only because it uses the same-named instance variable as it's backing (it has to store the value somewhere). Consider that attr_accessor :x
is equivalent to:
def x; @x; end
def x= (y); @x = y; end
快乐编码.
这篇关于在 Ruby/Rails 模型/控制器中引用关联/属性时 *、self.* 和 @* 之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!