2012-05-22 28 views
2

如何在Rails的ActiveRecord的緩存3.2.3如何ActiveRecord的高速緩存中的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 

什麼時候到表演動作緩存回報爲零的請求?

回答

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 

有關詳細信息獲取看到: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch

+1

無論緩存命中/未命中,Rails.cache.fetch(id,find(id))是否總是命中DB? –

0

鐵軌API說 - 如果c中沒有這樣的數據疼痛(一個緩存未命中),那麼將返回零。這是你的問題嗎?

順便說一下,請確保在「active_stocks」更改時更新緩存。