Search code examples
ruby-on-rails-3cachingaction-caching

Rails action caching refresh after expire


I'm looking to expire and then refresh the cache for a controller action using a publicly accessible endpoint.

In my app currently, /all returns cached json, and /update expires the cache. You can see the existing relevant code below. What I'd like to do is not only expire the cache but force a refresh. So, my question is:

Is there is a way to initiate the refresh of an action cache after expiring it, without hitting the action?

If the answer to that is no (as I'm beginning to suspect), then what would be the best way to do this? I require the update action to return an HTTP 200 status, not a 301 redirect so just redirecting to /all isn't an option.

VendorsController

caches_action :all, :expires_in=>2.weeks

....

def all 
  respond_to do |format|
    format.json { render :json => Vendor.all }
    format.html { render :json => Vendor.all }
  end
end


....

def update
  render :nothing => true
  expire_action :action => :all
end

Solution

  • You should use write_fragment

    def update
      render :nothing => true
      expire_action :action => :all
    
      cache_path = ActionCachePath.new(self, {:action => :all}, false).path
      write_fragment(cache_path, render_to_string(:json => Vendor.all))
    end
    

    Source that may help: