我正在处理一个显示餐厅菜单的页面。我有 2 个模型:FoodMenu has_many :products 和 Product belongs_to :food_menu。这两种型号我都没有控制器。相反,我使用“pages_controller.rb”来显示每个 FoodMenu 及其具有“菜单”操作的产品:
def menus
@food_menus = FoodMenu.includes(:products).all
end
我想对菜单页面 (localhost:3000/menus) 使用动作缓存,它正在工作,但是当我更新、创建或销毁产品时,我无法让缓存过期。
在“pages_controller.rb”的顶部,我有:
caches_action :menus
cache_sweeper :pages_sweeper
我尝试使用此处的示例代码为 app/sweepers 中的 Product 和 FoodMenu 模型创建单独的清扫器:http://guides.rubyonrails.org/caching_with_rails.html#sweepers ,但这不起作用。然后,我在 SO 条目中读到清扫器应该观察控制器使用的所有模型,所以我认为这意味着我必须创建一个“pages_sweeper.rb”,它观察 Product 和 FoodMenu 模型并过期“菜单”动作。那也没有用。我究竟做错了什么?这是我现在在“pages_sweeper.rb”中的内容:
class PagesSweeper < ActionController::Caching::Sweeper
observe Product, FoodMenu
# If our sweeper detects that a Product was created call this
def after_create(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was updated call this
def after_update(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was deleted call this
def after_destroy(product)
expire_cache_for(product)
end
def after_create(food_menu)
expire_cache_for(food_menu)
end
# If our sweeper detects that a FoodMenu was updated call this
def after_update(food_menu)
expire_cache_for(food_menu)
end
# If our sweeper detects that a FoodMenu was deleted call this
def after_destroy(food_menu)
expire_cache_for(food_menu)
end
private
def expire_cache_for(product)
# Expire the menus action now that we added a new product
expire_action(:controller => 'pages', :action => 'menus')
# Expire a fragment
expire_fragment('all_available_products')
end
def expire_cache_for(food_menu)
# Expire the menus page now that we added a new FoodMenu
expire_action(:controller => 'pages', :action => 'menus')
# Expire a fragment
expire_fragment('all_available_food_menus')
end
end