I'm working on a page that displays a restaurant menu. I have 2 models: FoodMenu has_many :products and Product belongs_to :food_menu. I don't have controllers for either model. Instead, I am using a "pages_controller.rb" to display each FoodMenu and its Products with a "menus" action:
def menus
@food_menus = FoodMenu.includes(:products).all
end
I want to use Action Caching for the menus page (localhost:3000/menus), which is working, but I can't get the cache to expire when I update, create, or destroy a product.
At the top of "pages_controller.rb", I have:
caches_action :menus
cache_sweeper :pages_sweeper
I tried creating separate sweepers for the Product and FoodMenu models in app/sweepers using the example code here: http://guides.rubyonrails.org/caching_with_rails.html#sweepers, but that didn't work. Then, I read in a SO entry that the sweeper is supposed to observe all the models that the controller uses, so I assumed that meant I have to create a "pages_sweeper.rb" that observes both the Product and FoodMenu models and expires the "menus" action. That didn't work either. What am I doing wrong? Here is what I have right now in "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