2

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
tereško
  • 58,060
  • 25
  • 98
  • 150
manderson
  • 98
  • 13

1 Answers1

3

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:

Baldrick
  • 23,882
  • 6
  • 74
  • 79
  • Thanks for responding. However, two concerns. 1. Doesn't cache_page write to the disk, whereas action caching use memcache? 2. Since I'm rendering json right in the controller (arguably not the best pattern), there's no template for `vendors/all`, and so it doesn't know how to render that to a string. Thoughts? Thanks for your help. – manderson Feb 26 '13 at 18:28
  • @manderson I didn't notice you were using `cache_action`. I've updated my answer to use `write_fragment` instead, it may work. I've added links to rails sources of actions caching for more informations. For the point 2, use directly `render_to_string(:json => Vendor.all)`. It should work. – Baldrick Feb 26 '13 at 22:43
  • Awesome! Thanks so much for your help. write_fragment makes complete sense. I wouldn't have been able to write the cache_path line without your code, but my rails-fu is growing. – manderson Feb 27 '13 at 16:28