The after_initialize
and after_find
回调是两个特殊的回调。
定义回调的唯一方法after_find
and after_initialize
事件是将它们定义为methods
。如果您尝试将它们声明为handlers
,他们会被默默地忽略。
来自API http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
after_find
and after_initialize
每个都会触发回调
由查找器找到并实例化的对象,其中after_initialize
新对象实例化后触发
以及。
来自Guides http://guides.rubyonrails.org/active_record_callbacks.html#after-initialize-and-after-find
The after_initialize
每当活动时都会调用回调
Record 对象是通过直接使用 new 或当
记录是从数据库加载的。避免这种需要可能很有用
直接覆盖您的 Active Record 初始化方法。
The after_find
每当 Active Record 加载时都会调用回调
数据库中的一条记录。after_find
之前被调用after_initialize
如果两者都定义了。
The after_initialize
and after_find
回调没有前_*
同行,但它们可以像其他 Active 一样进行注册
记录回调。
class User < ActiveRecord::Base
after_initialize do |user|
puts "You have initialized an object!"
end
after_find do |user|
puts "You have found an object!"
end
end
>> User.new
You have initialized an object!
=> #<User id: nil>
>> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>
放在哪里after_initialize
and after_find
在 AR 对象生命周期中?
因为它们与所有其他回调不同,而且它们没有before_* 对应项,所以作者(指Guides http://guides.rubyonrails.org/active_record_callbacks.html#after-initialize-and-after-find作者在这里)可能有兴趣将它们分开,因为它们是特殊情况。
最后我同意把after_initialize
before before_validation
。可能是这样。