2012-09-06 121 views
1

我试图根据他们的配置文件有多少个视图在我的主页上列出用户。用户分页,并且我试图缓存用户并在配置文件获取新视图时使该缓存失效。Rails保持缓存查询而不是查询的结果

我的控制器代码:

def index 
    @users = Rails.cache.read(params[:page]) 
    if [email protected]? 
    flash[:info] = "Cache was hit." 
    else 
    flash[:info] = "Miss." 
    @users = User.paginate(page: params[:page], per_page: 5, order: "views DESC") 
    Rails.cache.write(params[:page], @users) 
    end 
end 

当我第一次去2页,我得到预期高速缓存未命中,当我刷新,我得到一个高速缓存命中,也符合市场预期。但是,当我通过控制台手动更改了用户的views并刷新了第2页时,我在控制台中所做的更改影响了页面,即使该页面应该从缓存中呈现。顶部的通知仍然表示“Cache被击中”。

在控制台中运行Rails.cache.read("2")拉了一下我的控制器高速缓存给了我这个:

User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY views DESC LIMIT 5 OFFSET 0 
(0.2ms) SELECT COUNT(*) FROM "users" 
=> users freshly pulled from the database 

手动缓存通过控制台没有显示查询User.paginate值时Rails.cache.read被称为:

test = User.paginate(page: 1, order: "views DESC") 
=> users freshly pulled from the database 
Rails.cache.write("9", test) 
=> true 
Rails.cache.read("9") 
=> users from test; no queries displayed above this 

我不知道为什么我的控制器代码缓存查询而不是结果。任何建议将不胜感激。

回答

0

IIRC ActiveRecord现在是“懒惰”,你只是缓存查询对象。在User.paginate()之后尝试追加.all来强制sql运行,给你一个缓存结果集。

如果.all失败,请尝试使用.map/.select/.inject。

+0

谢谢!使用'.all'解决了这个问题。不知道ActiveRecord是懒惰的。 – user1650177