2

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
Matthew Boston
  • 1,320
  • 10
  • 24
  • Try without '/' in controller option: expire_action(:controller => 'posts', :action => 'index') – cthulhu Dec 28 '12 at 14:20
  • @cthulhu that doesn't work either. I tried using the '/' because of https://github.com/rails/rails/issues/3546. – Matthew Boston Dec 28 '12 at 14:30
  • I am getting this error "undefined method `cache_sweeper' for NormalReservationsController: Class Did you mean? cache_store" – Giridharan Oct 01 '19 at 08:35

1 Answers1

3

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

Matthew Boston
  • 1,320
  • 10
  • 24