How to invoke a rails sweeper in this scenario?

226 views Asked by At

As you can see from code below. I am caching the show action. I also have the following method in the show action View.create_for(@song).

I would like to make it so, when View.create_for(@song) is called, it clears out the respective cache.

How would I go about this? Do I have to manually invoke the rails sweeper in the View model? If so, how?

My controller:

class SongsController < ApplicationController
  caches_action :show, :cache_path => (proc do 
    song_path(params[:id], :user_id => user_signed_in? ? current_user.id : nil)
  end)

  # I tried with the following line, but this is not what I want. I only want to call the sweeper when `View.create_for(@song)` is called:
  # cache_sweeper :views_sweeper, :only => [:show]

  def show
    @song = Song.find(params[:id])
    View.create_for(@song)
  end
end

My Sweeper:

class SongsSweeper < ActionController::Caching::Sweeper
  observe Song

  def after_save(song)
    expire_fragment(/songs\/#{song.id}\/.*?/)
  end
end
1

There are 1 answers

0
twmills On BEST ANSWER

I think you should be referring to the songs_sweeper, not the views_sweeper:

cache_sweeper :songs_sweeper, :only => [:show]

I'm not sure of your requirements, but you could also be more specific in your SongsSweeper by changing after_save to after_create:

class SongsSweeper < ActionController::Caching::Sweeper
  observe Song

  def after_create(song)
    expire_fragment(/songs\/#{song.id}\/.*?/)
  end
end