Take the 2-minute tour ×

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 = Category.all

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

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?


share|improve this question
add comment

2 Answers

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
share|improve this answer
Ya that's close I have been using... I figured out why it wasn't working see below. –  Nick Faraday Feb 14 '10 at 0:55
add comment

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"
share|improve this answer
add comment

Your Answer


