ruby-on-railsruby-on-rails-3cachingsweeperaction-caching

Unable to expire_action on Rails


tl;dr

My expire_index method below is getting called, I see the puts in the logs. However, when I refresh the page is the stale version.

note: I am using rails_admin for updating the models. But have also noticed the same behavior using rails console directly.

Thanks for your help. Much appreciated!

details

app/controllers/posts_controller.rb

class PostsController < ApplicationController
  caches_action :index
  cache_sweeper :post_sweeper

  def index
    @posts = Post.published
  end

  def show
    @post = Post.find(params[:id])
   end
end

app/sweepers/post_sweeper.rb

class PostSweeper < ActionController::Caching::Sweeper
  observe Post

  def after_save(post)
    puts "======================"
    puts "      AFTER SAVE      "
    puts "======================"
    expire_index
  end

  private
  def expire_index
    puts "======================"
    puts "   EXPIRING INDEX     "
    puts "======================"
    expire_action(:controller => '/posts', :action => 'index')
  end
end

config/environments/production.rb

config.action_controller.perform_caching = true
config.cache_store = :dalli_store # using memcachier on heroku

Solution

  • Got it to work. Here's what it took:

    def expire_index
      cache_key = "views/#{request.host_with_port}/posts"
      Rails.cache.delete(cache_key)
    end
    

    More details on this gist -> https://gist.github.com/4400728