在这种情况下如何调用 Rails Sweeper?

发布于 2024-12-28 10:06:23 字数 929 浏览 2 评论 0原文

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

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

我该怎么办呢?我是否必须在 View 模型中手动调用 Rails Sweeper?如果是这样,怎么办?

我的控制器:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栀子花开つ 2025-01-04 10:06:23

我认为你应该指ongs_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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文