存储数据库查询时出现低级别缓存错误

时间:2013-01-09 02:24:24

标签: ruby-on-rails ruby-on-rails-3

我正在尝试通过缓存数据库查询来提高应用程序的性能。这些是简单的查询,因为我需要加载和缓存所有对象。

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

我可以在这里做些什么来缓解工作?有没有更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

我通过在Rails.cache.fetch中存储编码的JSON而不是原始的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