Rails控制器操作中的查询缓存



我正在为用户控制器索引操作使用查询缓存。

def index
@users = User.all
json_response @users
end

我按照轨道播放视频,并在用户控制器中添加了这样的内容。

def index
@users = User.cached_data
json_response @users
end

在用户模型中,我添加了cached_data方法。

def self.cached_data
Rails.cache.fetch([])   // I am not getting how to do caching here and get all the users data
end

有人能帮我解决这个问题吗。感谢

您想将Rails.cache.fetch制作成这样的块:

def self.cached_data
Rails.cache.fetch("all_users", expires_in: 2.hours) do
# add your query here
User.all
end
end

cache_key可以是你想要的任何东西,expires_in:是可选的,但我总是在那里添加它,除非cache_key基于时间戳或其他会自动使缓存过期的东西。

此外,此文档页仍然有效:

https://guides.rubyonrails.org/caching_with_rails.html#low-级别缓存

最新更新