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
我不知道为什么我的控制器代码缓存查询而不是结果。任何建议将不胜感激。
谢谢!使用'.all'解决了这个问题。不知道ActiveRecord是懒惰的。 – user1650177