如何在 Rails 3.2.3 中激活记录缓存
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
对显示操作缓存的请求何时返回 nil?
最佳答案
很难理解您在 Controller 中的意图,因为您的 show 和 index 方法具有相同的实现。
话虽如此,您可能希望将任何缓存逻辑移至此处的模型中,这样就可以更轻松地隔离您的问题。
请考虑以下重构:
股票 Controller :
def index
@stocks = Stock.active_for_restaurant(params[:restaurant_id])
end
def show
@stock = Stock.fetch_from_cache(params[:id])
end
股票.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
有关获取的更多信息,请参阅: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch
关于ruby-on-rails-3 - 如何在 Rails 3.2.3 中激活记录缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10700611/