Rails caching: using sweepers for actions that require parameters

I am trying to use sweepers to handle updated pages. To update index actions, etc. Everything works fine ... but I can't seem to have sweepers interpret page settings. If someone tells me what is wrong with the code below, I will be very grateful:

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 a cache but does not update it (ever). If I put 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 

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 
+4
source share
1 answer

If we assume that you copied and pasted the code, then the typo is also in your code. Since you did not receive a Rails error, we can assume that the sweepers are not being called. (i.e. after_update is not called). I would add a few log messages to make sure this is true.

Questions relate to the message:

  • Is this a sign of ActiveRecord :: Base?
  • Do you have other callbacks that return false and thereby stop the chain?

Sweeping examples on the network sequentially place the cache_sweeper line after the caches_xxx lines. I would be surprised if that matters, but worth checking out.

+1
source

Source: https://habr.com/ru/post/1336991/


All Articles