10

I have a controller index action which returns json output.

render :json => my_array.to_json

What type of caching do I have to use here. Does 'page caching' make sense for this.

Or do I have to do action caching like below

caches_action :index

2 Answers 2

4

Either action caching or page caching would work fine; page caching would have the benefit of never calling the Rails stack, but it depends on whether you need to control who accesses that Json feed.

I'm a big fan of using page caching if you can get away with it - there are big savings on system resources to be had. :)


EDIT: Page caching example, in case there was any confusion:

class SomeController < ApplicationController
  caches_page :index
  def index
    render :json => my_array.to_json
  end
end

Unless I've misunderstood something, that should be all you need to do.

5
  • how do I specify page caching for json. I don't have any template in my view?
    – user290870
    Commented May 12, 2010 at 7:33
  • You should just be able to specify it in the controller, added the code to my answer.
    – robotmay
    Commented May 12, 2010 at 7:41
  • thanks!. I thought page caching required the name of the view being cached as the argument to 'caches_page' instead of the action.
    – user290870
    Commented May 12, 2010 at 8:10
  • Ah ha, an easy mistake to make. Glad that's working for you. :)
    – robotmay
    Commented May 12, 2010 at 8:20
  • 2
    However, it won't be served with the correct Content-Type. For that you need to adjust your virtual host (if using Apache, for example) to specify that content type, or manually cache the JSON and serve it from your action. Commented Oct 25, 2011 at 22:52
2

Same considerations should apply to JSON as any other output. If you need to validate access to the data for the user, then action caching is the way to go, otherwise page caching should be fine.

If the data changes due to logic in your app, then both forms of caching are problematic and you are better off using something else.

1
  • 1
    how do I specify page caching for json. I don't have any template in my view?
    – user290870
    Commented May 12, 2010 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.