I’m trying to increase performance in my application by caching database queries. These are simple queries since I need to load and cache all objects.
Here’s a shortened version of my application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
def show_all
load_models
respond_to do |format|
format.json { render :json => {"items" => @items}
}
end
end
protected
def load_models
@items = Rails.cache.fetch "items", :expires_in => 5.minutes do
Item.all
end
end
end
But when I try and load this page I get this error:
ArgumentError in ApplicationController#show_all
undefined class/module Item
I’ve been following low-level caching guides by Heroku posted here: https://devcenter.heroku.com/articles/caching-strategies#low-level-caching
Any ideas what I can do here to get caching working? Is there a better way to accomplish this?
I fixed this issue by storing encoded JSON in
Rails.cache.fetchinstead of the raw ActiveRecord objects. I then retrieve the stored JSON, decode it, and render it for the view. The finished code looks like this: