2013-01-09 111 views
0

我试图通过缓存数据库查询来提高应用程序的性能。这些都是简单的查询,因为我需要加载和缓存所有对象。存储数据库查询时发生低级缓存错误

这里是我的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 

但是当我尝试并加载这个页面我得到这个错误:

ArgumentError in ApplicationController#show_all 
undefined class/module Item 

我一直在关注低级别的缓存Heroku的指南贴在这里:https://devcenter.heroku.com/articles/caching-strategies#low-level-caching

任何想法,我可以在这里做缓存工作?有没有更好的方法来实现这一点?

回答

0

我通过将编码的JSON存储在Rails.cache.fetch而不是原始ActiveRecord对象中解决了此问题。然后,我检索存储的JSON,将其解码并呈现给视图。完成的代码如下所示:

def show_all 
    json = Rails.cache.fetch "Application/all", :expires_in => 5.minutes do 
     load_models 
     obj = { "items" => @items } 
     ActiveSupport::JSON.encode(obj) 
    end 

    respond_to do |format| 
     format.json { render :json => ActiveSupport::JSON.decode(json) } 
    end 
    end 

    def load_models 
    @items = Item.all 
    end