我已經完成了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) –