2012-05-22 4 views
2

어떻게 레일에 캐시를 액티브하는 액티브합니다 3.2.3어떻게 레일에서 캐시 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 

때 않는 show 액션 캐시 반환 전무에 요청?

답변

3

그것은 당신의 쇼와 인덱스 방법 모두 동일한 구현이 있기 때문에, 여기 컨트롤러에있는 당신의 의도를 이해하기 어렵다. 그와

은 당신이, 그때는 문제를 분리하기 쉬울 것입니다 여기에 모델의 모든 캐싱 논리를 이동할 가능성이 높습니다 말했다되고.

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 :

다음과 같은 리팩토링을 고려하시기 바랍니다 http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch

+1

하지'Rails.cache.fetch (ID, 발견 (ID))'에 관계없이 항상 캐시 히트의 DB에 충돌/그리워 할 것인가? –

0

를 API를 레일로 :에 대한 추가 정보를 원하시면

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 

를 참조 가져 오기 말한다 - C에 그러한 데이터가없는 경우 ache (캐쉬 미스)이면 nil이 반환됩니다. 그게 네 질문이야?

그런데 "active_stocks"가 변경되면 캐시를 업데이트해야합니다.

관련 문제