为什么 ActiveRecord 回调需要实例变量或实例方法以 self 关键字为前缀? [英] Why do ActiveRecord callbacks require instance variables or instance methods to be prefixed with self keyword?
问题描述
ActiveRecord 有几个不同的回调方法用于简化模型逻辑.例如 after_find
和 before_create
方法.
ActiveRecord has a few different callback methods used to simplify model logic. For example after_find
and before_create
methods.
考虑这个代码示例:
class ExternalPrintingCard < ActiveRecord::Base
belongs_to :user
belongs_to :ph_user
after_create :change_pin
def change_pin
self.user.randomize_printer_pin
end
def after_find
return if self.card_status == false
self.card_status = false if self.is_used_up?
self.card_status = false if self.is_expired?
self.save!
end
end
如果我从实例变量或实例方法中删除所有 self
前缀,这两个回调将被调用,但它们就好像它们是这些回调方法中的局部变量.
If I remove all the self
prefixes from the instance variables or instance methods, these 2 callbacks will be called, but it is as if they are local variables inside these callback methods.
这个实例变量(card_status
)、实例方法(save!
、is_used_up?
和 is_expired?
)和关联 (user
) 在没有 self
前缀的这两个回调方法之外工作正常.
This instance variable (card_status
), instance methods (save!
, is_used_up?
and is_expired?
) and association (user
) worked fine outside these 2 callback methods without the self
prefix.
Rails 文档中关于回调方法(实例方法)的示例代码,似乎总是使用 self
前缀,即使它正在调用实例变量或方法,正确地它们无需self
前缀通常.
The sample code in the Rails' documentation for callback methods (instance methods), seems to always use the self
prefix even though it is calling instance variables or methods, which by right they are accessible without the self
prefix normally.
我希望对 ActiveRecord 回调有更好理解的人可以帮助阐明这种行为.
I hope someone with a better understanding of ActiveRecord callbacks can help to shed a light on this behaviour.
干杯
推荐答案
技术上你只需要在赋值方法前使用 self 即可.这对于区分带有尾随 = 的实例方法和对局部变量的赋值是必要的.
Technically you only need to use the self in front of the assignment methods. This is necessary to differentiate between a instance method with trailing = and an assignment to a local variable.
这篇关于为什么 ActiveRecord 回调需要实例变量或实例方法以 self 关键字为前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!