我注意到当回调符号作为输入传递时,Rails不会触发after_initialize
回调。
下面的代码不起作用。
class User < ActiveRecord::Base
after_initialize :init_data
def init_data
puts "In init_data"
end
end
下面的代码有效。
class User < ActiveRecord::Base
def after_initialize
init_data
end
def init_data
puts "In init_data"
end
end
有人可以解释这种行为吗?
注意1
ActiveRecord documentation说了有关
after_initialize
的以下内容:Unlike all the other callbacks, after_find and after_initialize will
only be run if an explicit implementation is defined (def after_find).
In that case, all of the callback types will be called.
虽然说after_initialize需要显式实现,但是我发现上一段中的第二句话是模棱两可的,即
In that case, all of
the callback types will be called.
什么是all of the call back types
?文档中的代码示例包含一个不使用显式实现的示例:
after_initialize EncryptionWrapper.new
最佳答案
根据documentation,您不能对after_initialize
或after_find
回调使用宏风格的类方法:
The after_initialize and after_find callbacks are a bit different from the others. They have no before_* counterparts, and the only way to register them is by defining them as regular methods. If you try to register after_initialize or after_find using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since after_initialize and after_find will both be called for each record found in the database, significantly slowing down the queries.
简而言之,您必须定义一个
after_initialize
实例方法:class User < ActiveRecord::Base
def after_initialize
do_stuff
end
end
关于ruby-on-rails - ActiveRecord:方法名称作为符号传递时,不调用after_initialize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3826153/