Caching a 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'm noticing that whenever a request is made to /tags, Rails开发者_JAVA技巧 is generating a cache file at /public/tags.json. However, it never seems to use this cache file. Instead, it always runs the 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 isn't Rails using the cache file that's being generated? Is it because the request is for /tags and not /tags.json?
i think you are probably correct, you can specify the :cache_path
option to tell it what to name the file so do
caches_page :index, :cache_path => '' # if not try 'tags'
you can also pass a proc, if you want to include params
caches_page :index , :cache_path => Proc.new {|controller| controller.params }
or anything else
Your cache directory could be in the wrong place. I had this issue before where I was trying to place the cache in a directory other than public.
精彩评论