【问题标题】:Order of after_commit callbacks in RailsRails 中 after_commit 回调的顺序
【发布时间】:2020-06-02 08:57:37
【问题描述】:

模型Item 有一个after_commit 回调调用say updated_related

class Item < ActiveRecord::Base
    after_commit :updated_related        
    def updated_related
      # update related items based on latest item
    end
end

另外,一个名为ItemObserver 的观察者有一个名为clear_item_cacheafter_commit

class ItemObserver < ActiveRecord::Observer
    def after_commit
      #clear item from cache
    end
end

现在的问题是 update_related 在调用观察者之前首先被调用,因此相关项目在陈旧的 item 条目上被调用。

我如何确保首先调用观察者的回调,因为它是 item 的一部分,之后我想运行相关项目以运行?

附:从观察者回调中删除代码或完全删除回调现在不是一种选择。 我在 Rails 4 上并使用 rails-observable 宝石作为 Observable。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 callback


    【解决方案1】:

    你不能让观察者的回调被首先调用,来自doc

    观察者中的回调总是在回调之后被调用 在模型中定义

    你应该将updated_related方法的所有逻辑移动到观察者的after_commit中,然后你可以控制你想要的任何顺序。

    或者你可以在updated_relatedafter_commit之间交换代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      相关资源
      最近更新 更多