2

I have the following setup: A model called Categories. These categories are managed using ActiveAdmin. I want to cache the categories using page caching.

This is how I've setup my app/admin/categories.rb

ActiveAdmin.register Category do
    controller do 
        cache_sweeper :category_sweeper
    end
end

This is my sweeper:

class CategorySweeper < ActionController::Caching::Sweeper
  observe Category

  def after_save(category)
    expire_cache(category)
  end

  def after_destroy(category)
    expire_cache(category)
  end

  def expire_cache(category)
    expire_page :controller => 'categories', :action => 'index', :format => 'json'
  end
end

And here is my controller:

class CategoriesController < ApplicationController
    caches_page :index
  cache_sweeper :category_sweeper

    respond_to :json

    def index
      @categories = Category.all 
      respond_with(@categories)
    end

    def show
      CategorySweeper.instance.expire_cache(@category)
      respond_with('manually sweeped!')
    end
end

So the idea is when there is a change in the active admin the sweeper should get invoked. I set up debug.log and turns out it's working. But for some reason the cache does not expire!

But, if I do the show action (i.e. go to /categories/1.json then my manual sweeper kicks in and it works fine). So why is the sweeper only working when I invoke it and not when there is a change in the admin?

Thanks in advance, -David

bobbypage
  • 2,157
  • 2
  • 21
  • 21

1 Answers1

2

Your ActiveAdmin controller located in different namespace, see this SO question.

Shortly:

Add slash into cache expiration url code:

def expire_cache(category)
  expire_page :controller => '/categories', :action => 'index', :format => 'json'
end
Community
  • 1
  • 1
Mark Huk
  • 2,379
  • 21
  • 28
  • Hey, thanks so much it finally works. I have one question though: in my routes I use a scope to make the url /api/v1/categories.json . So in that sense for the controller I should do /api/v1/categories. But if I try that then the cache is not clearing. But your solution works great if the url is just /categories.json. Any ideas? – bobbypage May 05 '12 at 21:40
  • Try `path_prefix` as argument. – Mark Huk May 06 '12 at 21:07