0

从下面的代码可以看出。我正在缓存show动作。我在 show action 中也有以下方法View.create_for(@song)

我想这样做,当View.create_for(@song)被调用时,它会清除相应的缓存。

我该怎么办?我是否必须手动调用View模型中的导轨清扫器?如果是这样,怎么做?

我的控制器:

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

我的扫地机:

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

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

1 回答 1

1

我认为您应该指的是songs_sweeper,而不是views_sweeper:

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

我不确定您的要求,但您也可以通过将 after_save 更改为 after_create 在 SongsSweeper 中更具体:

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

  def after_create(song)
    expire_fragment(/songs\/#{song.id}\/.*?/)
  end
end
于 2012-01-22T19:28:28.147 回答