Caching JSON Result in Rails

I have the following controller that returns a list of tags when it receives an HTTP request to / tags

class TagsController < ApplicationController
  caches_page :index

  def index
    respond_to do |format|
      format.json {
        render :json => Tag.all(:order => "name").to_json
      }
    end
  end
end

I notice that whenever a request / tag is made, Rails generates a cache file in /public/tags.json. However, it never uses this cache file. Instead, it always runs an SQL query to retrieve the tags:

Started GET "/tags" for 127.0.0.1 at 2011-06-15 08:27:29 -0700
  Processing by TagsController#index as JSON
  Tag Load (0.7ms)  SELECT "tags".* FROM "tags" ORDER BY name
Write page <project root path>/public/tags.json (0.3ms)
Completed 200 OK in 35ms (Views: 1.1ms | ActiveRecord: 0.7ms)

Why doesn't Rails use the generated cache file? Is this because the request is for / tags, not / tags.json?

+5
source share
2 answers

I think you are probably right, you can specify an option :cache_pathto tell her what to name the file, so

caches_page :index, :cache_path => '' # if not try 'tags'

you can also pass proc if you want to include parameters

caches_page :index , :cache_path => Proc.new {|controller| controller.params }

or anything else

+2

. , , .

0

All Articles