我正在尝试实现一个Cache Sweeper,它将过滤特定的控制器操作。

class ProductsController < ActionController
    caches_action :index
    cache_sweeper :product_sweeper

    def index
        @products = Product.all
    end

    def update_some_state
      #... do some stuff which doesn't trigger a product save, but invalidates cache
    end
end


清扫器类:

class ProductSweeper < ActionController::Caching::Sweeper
    observe Product

    #expire fragment after model update
    def after_save
       expire_fragment('all_available_products')
    end

    #expire different cache after controller method modifying state is called.
    def after_update_some_state
        expire_action(:controller => 'products', :action => 'index')
    end
end


ActiveRecord回调“ after_save”将正常工作,但似乎从未调用控制器操作“ after_update_some_state”上的回调。

最佳答案

似乎在尝试使控制器操作的回调正常工作时,我只是缺少控制器名称。我的清扫器应为:

class ProductSweeper < ActionController::Caching::Sweeper
    observe Product

    #expire fragment after model update
    def after_save
       expire_fragment('all_available_products')
    end

    #expire different cache after controller method modifying state is called.
    def after_products_update_some_state
        expire_action(:controller => 'products', :action => 'index')
    end

    #can also use before:
    def before_products_update_some_state
        #do something before.
    end
end

10-04 23:35