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

キャッシングを機能させるためにここでできることはありますか? これを達成するためのより良い方法はありますか?

4

1 に答える 1

0

Rails.cache.fetch生の ActiveRecord オブジェクトの代わりにエンコードされた JSON を保存することで、この問題を修正しました。次に、保存された 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
于 2013-01-09T16:46:08.760 に答える