我已经完成了ActiveRecord回调的源代码;我可以看到ActiveRecord的涉及一种用于像这样的回调:ActiveRecord回调如何在Rails中实际工作
module Callbacks
extend ActiveSupport::Concern
CALLBACKS = [
:after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
:before_save, :around_save, :after_save, :before_create, :around_create,
:after_create, :before_update, :around_update, :after_update,
:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
]
def destroy #:nodoc:
@_destroy_callback_already_called ||= false
return if @_destroy_callback_already_called
@_destroy_callback_already_called = true
_run_destroy_callbacks { super }
rescue RecordNotDestroyed => e
@_association_destroy_exception = e
false
ensure
@_destroy_callback_already_called = false
end
def touch(*) #:nodoc:
_run_touch_callbacks { super }
end
private
def create_or_update(*)
_run_save_callbacks { super }
end
def _create_record
_run_create_callbacks { super }
end
def _update_record(*)
_run_update_callbacks { super }
end
end
end
现在我可以看到,通过符号的阵列的恒定可用回调。
进一步的调查显示,回调函数中的create_or_update(*)
方法涉及从persistance.rb文件(它对模型执行CRUD操作)中调用 - 并使用像这样的行。
但是我不明白的是2个关键要素。
如何/哪里的ActiveRecord确实会触发回调,并在那里是产生为你传递给回调将要执行的方法的符号,它的方法。
ActiveRecord如何知道回调甚至退出?也就是说,它是如何从一个类声明发展到由ActiveRecord执行的?它被加载到某种寄存器中或者检查每个负载的东西;等等?
我认为它可能在[ActiveRecord :: Callbacks.included](https://apidock.com/rails/v2.3.8/ActiveRecord/Callbacks/included/class)和[ActiveRecord :: Observer#define_callbacks]( https://apidock.com/rails/ActiveRecord/Observer/define_callbacks) –