如何在Rails 3.2.3中使用activerecord缓存

时间:2012-05-22 10:54:36

标签: ruby-on-rails-3 caching activerecord memcached

如何在Rails 3.2.3中使用activerecord缓存

stocks_controller.rb:

def index
  @stocks = Rails.cache.read custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS)
  if @stocks.blank?
    @stocks = Stock.only_active_stocks(params[:restaurant_id])
    Rails.cache.write custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS), @stocks
  end
end

def show
  @stocks = Rails.cache.read custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS)
  if @stocks.blank?
    @stocks = Stock.only_active_stocks(params[:restaurant_id])
    Rails.cache.write custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS), @stocks
  end
end

对show动作缓存的请求何时返回nil?

2 个答案:

答案 0 :(得分:3)

这里很难理解你在控制器中的意图,因为你的show和index方法都有相同的实现。

话虽如此,您可能希望将任何缓存逻辑移到模型中,然后更容易隔离您的问题。

请考虑以下重构:

stocks_controller:

def index
  @stocks = Stock.active_for_restaurant(params[:restaurant_id])
end

def show
  @stock = Stock.fetch_from_cache(params[:id])
end

stock.rb:

def active_for_restaurant(restaurant_id)
  Rails.cache.fetch(custom_cache_path(restaurant_id, Const::ACTIVE_STOCKS)) do
    Stock.only_active_stocks(restaurant_id)
  end
end

def fetch_from_cache(id)
  Rails.cache.fetch(id, find(id))
end

有关fetch的更多信息,请参阅: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch

答案 1 :(得分:0)

正如rails api所说 - 如果缓存中没有这样的数据(缓存未命中),则返回nil。那是你的问题吗?

顺便说一下,确保在“active_stocks”发生变化时更新缓存。