Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 491
Kevin Pang Avatar asked Nov 05 '22 20:11

Kevin Pang


1 Answers

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

like image 149
loosecannon Avatar answered Nov 09 '22 06:11

loosecannon