我正在顯示餐廳菜單的頁面上工作。我有2個模型:FoodMenu has_many:產品和產品belongs_to:food_menu。我沒有這兩種型號的控制器。取而代之的是,我使用的是「pages_controller.rb」顯示每個FoodMenu及其產品具有「菜單」行動:Rails 3緩存:如何使用帶有Action和Fragment緩存的清掃器來使緩存過期?
def menus
@food_menus = FoodMenu.includes(:products).all
end
我想用行動緩存菜單頁面(本地主機:3000 /菜單)它正在工作,但當我更新,創建或銷燬產品時,我無法讓緩存過期。
在的「pages_controller.rb」前,我有:
caches_action :menus
cache_sweeper :pages_sweeper
我想在這裏使用的示例代碼在app /清掃創造產品單獨清潔工和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
這是否意味着片段緩存和動作緩存不能用於相同的緩存策略,即它是一個或另一個?我遇到了一個片段緩存過期問題,該片段緩存駐留在我正在使用caches_action的視圖的一部分中。 – Pete 2012-02-16 09:47:30