【问题标题】:How do ActiveRecord Callbacks actually Work in RailsActiveRecord 回调如何在 Rails 中实际工作
【发布时间】:2017-08-27 00:49:20
【问题描述】:

我已经浏览过 ActiveRecord 回调的源代码;我可以看到回调的 ActiveRecord 问题,如下所示:

  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 操作)调用 - 并使用@_trigger_update_callback = result 之类的行。

但我无法弄清楚的是 2 个关键要素。

  1. ActiveRecord 如何/在何处实际触发回调,该方法在哪里产生您传递给回调以执行的方法的符号。

  2. ActiveRecord 如何知道回调甚至退出了​​?也就是说,它是如何从一个类声明变成被 ActiveRecord 执行的?它是加载到某种寄存器中还是每次加载时检查的东西?等等?

【问题讨论】:

标签: ruby-on-rails ruby activerecord callback


【解决方案1】:

ActiveRecord 和 ActiveModel 使用 ActiveSupport::Callbacks 来做他们的脏活。

如果您查看其ClassMethods 模块,您会发现define_callbacks 定义(通过module_eval_run_update_callbacks 和朋友。 _run_*_callbacks 方法只是从主模块调用run_callbacks

所以回答你的问题:

  1. 我相信 ActiveRecord 实际上会触发您发布的代码中的回调。看起来ActiveRecord::Transactions 有几个在运行(与交易相关的,很有趣)。

  2. 无需深入挖掘,看起来run_callbacks 方法只是保留了所有回调的列表,然后遍历并找出什么是什么以及该做什么。

可能没有您希望的那么深入的答案,但希望这至少可以让您朝着正确的方向前进,自行挖掘和调查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多