Cómo activar la caché de registro en Rails 3.2.3
Frecuentes
Visto 2,603 veces
2
Cómo activar la caché de registro en 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
¿Cuándo devuelve cero una solicitud a la memoria caché de acción de la demostración?
2 Respuestas
3
Es difícil entender su intención en el controlador aquí, ya que tanto su método show como index tienen la misma implementación.
Habiendo dicho eso, es probable que desee mover cualquier lógica de almacenamiento en caché al modelo aquí, entonces será más fácil aislar su problema.
Considere el siguiente refactor:
controlador_de_acciones:
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
Para obtener más información sobre buscar, consulte: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch
contestado el 22 de mayo de 12 a las 14:05
0
Como dice Rails api: si no hay tales datos en el caché (una falla de caché), entonces se devolverá nil. ¿Es esa tu pregunta?
Por cierto, asegúrese de actualizar el caché cuando cambien las "acciones_activas".
contestado el 24 de mayo de 12 a las 00:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas ruby-on-rails-3 caching activerecord memcached or haz tu propia pregunta.
No lo hará
Rails.cache.fetch(id, find(id))
¿siempre acceda a la base de datos independientemente del acierto/fallo de la memoria caché? - Alistair A. Israel