我是一个 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 的产品。
它甚至没有击中我的控制器。
关键可能是路线,在我的 memcached 控制台中,我看到它是基于相同的密钥进行获取的。
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
这应该可以帮助您为每个用户拥有单独的缓存。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)