Rails action caching with querystring parameters
Asked Answered
G

3

40

How can I cache my REST controller with Rails where my actions have query string parameters?

Example: GET /products/all.xml?max_price=200

Thx!

Grainfield answered 1/1, 2010 at 13:57 Comment(0)
Y
94

If you want to cache an action, based on all the query parameters (or say on nearly all of them), you can do:

caches_action :my_action, :cache_path => Proc.new { |c| c.params }

Or, maybe you want all but some params that you just use for Analytics (but that have no bearing on the records you're fetching):

caches_action :my_action, :cache_path => Proc.new { |c| c.params.delete_if { |k,v| k.starts_with?('utm_') } }
Yolondayon answered 30/1, 2010 at 1:23 Comment(4)
Say the action has username john and you've cached a few versions of this based on random get parameters passed in. Is there a way to invalidate the cache for the action with username john AND all the cached versions with params? Example /john/picture?dimension=50 and /john/picture?dimension=100 is it possible to clear all the versions of johns picture?Krispin
@Marc: Yes, see namespacing for ideas code.google.com/p/memcached/wiki/…Easygoing
Hopefully this helps someone: In Rails 3- when expiring an action cache that has custom parameters, a format defined, AND you have set the default URL to ensure a trailing slash, expire_action(:action => :my_action, :param_1 => "val", :format => :json), rails does not use the correct cache key. Instead of clearing the cache key /my_action.json/?param_1=val it will clear /my_action.json/?param_1=val.json due to the way it infers the extension. github.com/rails/rails/blob/3-2-stable/actionpack/lib/…Kharif
So how would I expire the action when using the cache_path ?Readable
T
14

To use the request url as cache key I do something like this:

caches_action :index, :cache_path => Proc.new {|c| c.request.url }
Torquemada answered 20/2, 2010 at 2:0 Comment(0)
W
4

In this case you should use fragments caching:

in your controller:

cache(params[:max_price], :expires_in => 10.minute) do
  # get the result
end
Woodard answered 1/1, 2010 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.