ruby-on-railscachingsweeper

Rails Caching: Using sweepers for actions which require parameters


I'm trying to use sweepers to handle my page refreshes. For refreshing index actions, etc everything works fine...but I can't seem to sweepers to interpret page parameters. If anyone can tell me what's wrong with the code below, I'd be very appreciative:

Controller:

class PostsController < ApplicationController
  load_and_authorize_resource
  cache_sweeper :post_sweeper, :only => [:create, :update, :destroy]
  caches_page :index
  caches_page :show
  caches_action :edit, :new

  # This refreshes cache correctly
  def index
    @posts = Post.all
  end

# This creates cache, but does not refresh it (ever). If I place the expire_page command directly into the action (instead of the sweeper), it works fine

def update
    @post = Post.find(params[:id])
    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = t(:post_updated)
        format.html { redirect_to(@post) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

The sweeper:

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

  def after_create(record)
    expire_cache_for_index(record)
  end

  def after_update(record)
    expire_cache_for_index(record)
    expire_cache_for_post(record)
    expire_cache_for_edit(record)
  end

  def after_destroy(record)
    expire_cache_for_index(record)
    expire_cache_for_post(record)
    expire_cache_for_edit(record)
  end

  private
  def expire_cache_for_index(record)
    expire_page :controller => 'posts', :action => 'index'
  end

  def expire_cache_for_post(record)
    expire_page :controller => 'posts', :action => 'show', :id => record.id
  end

  def expire_case_for_edit(record)
    expire_action :controller => 'posts', :action => 'edit', :id => record.id
  end

end

Solution

  • If we assume you copy and pasted the code, then the typo is also in your code. Since you did not get flagged with an error by Rails, we can then assume that the sweepers are not being called. (i.e. the after_update is not being called). I would add some logger messages in to verify that that really is the case.

    Questions is about Post:

    1. Is it a decedent of ActiveRecord::Base?
    2. Do you have other callbacks that are returning false and thus stopping the chain?

    The sweeper examples on the net consistently put the cache_sweeper line after the caches_xxx lines. I'd be surprised if that makes a difference but its worth checking out.