Rails 缓存清扫器和模型回调触发

Top*_*gio 0 ruby-on-rails callback observer-pattern

我有以下课程:

class Vigil < ActiveRecord::Base
  after_update :do_something_cool

  private
    def do_something_cool
      # Sweet code here
    end
end

class NewsFeedObserver < ActionController::Caching::Sweeper
  observe Vigil

  def after_update
    # Create a news feed entry
  end
end
Run Code Online (Sandbox Code Playgroud)

一切都按预期进行;但是,after_updatein the clearer 需要do_something_cool模型中的方法已经完成才能正常运行。问题是after_updatedo_something_cool回调之前(或可能同时)调用了清扫器中的,这会导致问题。

有谁知道如何after_update在模型回调后强制清扫器中的 s 触发?有没有更好的方法来实现这一目标?

更新/修复:事实证明,与下面的答案不同,观察者回调实际上以正确的顺序触发(在模型回调之后)。当我发现这一点时,我意识到一定是其他地方出了问题。

do_something_cool方法销毁所有守夜人的插槽,并用正确数量的正确时间替换它们。观察者依靠插槽的数量来确定守夜应该持续多长时间。所以,潜在的问题是所有守夜人的插槽都被销毁了,并且数据被缓存了,所以当我vigil.slots从观察者那里调用时,它正在使用缓存(销毁的插槽)数据。解决方案:只需在结束时调用 vigil.slots(true)do_something_cool即可重新加载/重新缓存新创建的插槽!

dea*_*rne 5

它不会同时运行,但您是对的,看起来 Sweeper 回调在模型一之前运行。

这篇文章可能会有所帮助:http : //upstre.am/2007/10/27/using-and-testing-activerecordrails-observers/

大约一半时(搜索“回调:after_read”),他们尝试为观察者创建自定义回调。您可以使用它来创建一个 after_something_cool ARObserver 方法,该方法在模型完成时被调用,例如很酷

class Vigil < ActiveRecord::Base
  after_update :do_something_cool

  private
    def do_something_cool
      # Sweet code here
      callback :after_something_cool
    end
end

class NewsFeedObserver < ActionController::Caching::Sweeper
  observe Vigil

  def after_something_cool
    # Create a news feed entry
  end
end
Run Code Online (Sandbox Code Playgroud)

免责声明:我从来没有这样做过,而且我总是发现清扫器在不同版本的 Rails 之间脾气暴躁,所以对它们有用的东西可能对你不起作用:(