开发者

How do I return memcached string based on respond_to type?

开发者 https://www.devze.com 2022-12-20 05:33 出处:网络
I have a group of categories and I access these categorizes via javascript several times during the average course of use for my application via JSON.

I have a group of categories and I access these categorizes via javascript several times during the average course of use for my application via JSON.

So in my control currently I have a

@categories = Categor开发者_StackOverflow社区y.all

respond_to do |format|
  format.html # index.html.erb
  format.json 

along with the appropriate index.json.erb file that formats what I need as far as JSON.

Now I want to add some memcached functionality to this so in the index.json.erb file I have added

<% cache "JSON_CATEGORIES_ALL" do -%> block around my output

My question is how do I get my controller to call this cache key when responding to a JSON request and act normally, pulling from the database, on other calls?

Thanks


You can check the format of the request:

@categories = Category.all unless request.format == "application/json" and fragment_exists?("JSON_CATEGORIES_ALL")

respond_to do |format|
  format.html # @categories is available
  format.json # no database call if your cache fragment already exists
end


I figured it out... for anyone who stumbles upon this here it is.

@categories = Category.all unless request.format == "application/json" and Rails.cache.exist?("views/JSON_CATEGORIES_ALL")

NOTICE: the addition of views/ to the cache key! seems rails prepends this to caches made on a view.

agregoire: Thanks for the

request.format == "application/json"
0

精彩评论

暂无评论...
验证码 换一张
取 消