views:

25

answers:

2

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
  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

+1  A: 

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
agregoire
Ya that's close I have been using... I figured out why it wasn't working see below.
Nick Faraday
A: 

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"
Nick Faraday