簡體   English   中英

Rails Action Caching用於用戶特定的記錄

[英]Rails Action Caching for user specific records

我是Rails新手,正在嘗試為我的應用程序實現緩存。 我安裝了memcached並將其配置在development.rb中,如下所示:

config.action_controller.perform_caching             = true
config.cache_store = :mem_cache_store

我有一個控制器ProductsController,用於在用戶登錄時顯示特定於用戶的產品。

class ProductsController < ApplicationController
  caches_action :index, :layout => false
  before_filter :require_user

  def index
    @user.products              
  end
end

The route for index action is: /products

問題是當我登錄為

1)第一次用戶A,Rails擊中了我的控制器並緩存了產品操作。

2)我以用戶B的身份注銷並登錄,它仍然以用戶A的身份登錄並顯示用戶A而不是用戶B的產品。它甚至沒有擊中我的控制器。

密鑰可能是路由,在我的內存緩存控制台中,我看到它是基於相同的密鑰來獲取的。

20 get views/localhost:3000/products
20 sending key views/localhost:3000/products

動作緩存不是我應該使用的嗎? 我將如何緩存和顯示特定於用戶的產品?

謝謝你的幫助。

第一個問題是您的require_user的before_filter在操作緩存之后,因此不會運行。 要解決此問題,請使用以下控制器代碼:

class ProductsController < ApplicationController
  before_filter :require_user
  caches_action :index, :layout => false

  def index
    @products = @user.products              
  end
end

其次,對於動作緩存,您正在執行與頁面緩存完全相同的操作,但是在運行過濾器之后,因此您的@ user.products代碼將不會運行。 有兩種方法可以解決此問題。

首先,如果需要,您可以根據傳遞給頁面的參數來緩存操作。 例如,如果傳遞user_id參數,則可以基於該參數進行緩存,如下所示:

caches_action :index, :layout => false, :cache_path => Proc.new { |c| c.params[:user_id] }

其次,如果您只想緩存查詢而不是整個頁面,則應完全刪除操作緩存,而僅緩存查詢,如下所示:

def index
  @products = Rails.cache.fetch("products/#{@user.id}"){ @user.products }
end

這應該可以幫助您為每個用戶使用單獨的緩存。

基於Pan Thomakos的答案,如果您要從處理身份驗證的控制器繼承,則需要從父類中復制before_filter。 例如:

class ApplicationController < ActionController::Base
  before_filter :authenticate
end

class ProductsController < ApplicationController
  # must be here despite inheriting from ApplicationController
  before_filter :authenticate
  caches_action :index, :layout => false
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM