使用查询字符串参数进行Rails操作缓存

xpe*_*int 40 caching controller ruby-on-rails

如何在我的操作具有查询字符串参数的情况下使用Rails缓存我的REST控制器?

Example: GET /products/all.xml?max_price=200
Run Code Online (Sandbox Code Playgroud)

谢谢!

chr*_*ley 88

如果要基于所有查询参数(或几乎所有查询参数)缓存操作,您可以执行以下操作:

caches_action :my_action, :cache_path => Proc.new { |c| c.params }
Run Code Online (Sandbox Code Playgroud)

或者,您可能只想要一些仅用于分析的params(但与您正在获取的记录无关):

caches_action :my_action, :cache_path => Proc.new { |c| c.params.delete_if { |k,v| k.starts_with?('utm_') } }
Run Code Online (Sandbox Code Playgroud)

  • 那么在使用 cache_path 时如何使操作过期? (2认同)

小智 10

要将请求URL用作缓存键,我执行以下操作:

caches_action :index, :cache_path => Proc.new {|c| c.request.url }
Run Code Online (Sandbox Code Playgroud)