Rails Action Caching用于用户特定的记录 [英] Rails Action Caching for user specific records
问题描述
我是Rails新手,正在尝试为我的应用程序实现缓存. 我安装了memcached并将其配置在我的development.rb中,如下所示:
I am a rails newbie trying to implement caching for my app. I installed memcached and configured it in my development.rb as follows:
config.action_controller.perform_caching = true
config.cache_store = :mem_cache_store
我有一个控制器ProductsController,可以在用户登录时显示特定于用户的产品.
I have a controller ProductsController that shows user specific products when they are logged in.
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击中了我的控制器并缓存了产品操作.
1) User A for the first time, rails hits my controller and caches the products action.
2)我以用户B的身份注销并登录,它仍然以用户A的身份登录,并显示了用户A而非用户B的产品. 它甚至没有击中我的控制器.
2) I logout and login as User B, it still logs me in as User A and shows products for User A and not User B. It doesn't even hit my controller.
关键可能是路由,在我的内存缓存控制台中,我看到它是基于同一密钥获取的.
The key probably is the route, in my memcached console I see that it's fetching based on the same key.
20 get views/localhost:3000/products
20 sending key views/localhost:3000/products
动作缓存不是我应该使用的缓存吗?我将如何缓存和显示特定于用户的产品?
Is action caching not what I should use? How would I cache and display user specific products?
感谢您的帮助.
推荐答案
第一个问题是,您的require_user的before_filter在操作缓存之后,因此不会运行.要解决此问题,请使用以下控制器代码:
The first problem is that your before_filter for require_user is after the action caching, so that won't run. To fix that, use this controller code:
class ProductsController < ApplicationController
before_filter :require_user
caches_action :index, :layout => false
def index
@products = @user.products
end
end
第二,对于动作缓存,您正在执行与页面缓存完全相同的操作,但是在运行过滤器之后,您的@ user.products代码将不会运行.有两种方法可以解决此问题.
Second, for action caching you are doing the exact same thing as page caching, but after filters are run, so your @user.products code won't run. There are a couple of ways to fix this.
首先,如果需要,您可以根据传递给页面的参数来缓存操作.例如,如果传递user_id参数,则可以基于该参数进行缓存,如下所示:
First, if you want you can cache the action based on the parameters that are passed to the page. For example, if you pass a user_id parameter, you could cache based on that parameter like this:
caches_action :index, :layout => false, :cache_path => Proc.new { |c| c.params[:user_id] }
第二,如果要仅缓存查询而不是整个页面,则应完全删除操作缓存,而仅缓存查询,如下所示:
Second, if you want to simply cache the query and not the entire page, you should remove action caching entirely and only cache the query, like this:
def index
@products = Rails.cache.fetch("products/#{@user.id}"){ @user.products }
end
这应该有助于您为每个用户使用单独的缓存.
This should help you get on your way to having a separate cache for each user.
这篇关于Rails Action Caching用于用户特定的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!