Ruby on rails 当模型作为键给定时,Rails.cache.fetch不工作
我的印象是我们可以给Rails一个模型(任何响应Ruby on rails 当模型作为键给定时,Rails.cache.fetch不工作,ruby-on-rails,caching,Ruby On Rails,Caching,我的印象是我们可以给Rails一个模型(任何响应to_param或cache_key)到Rails.cache.fetch,它将创建一个键并缓存块的响应 我有以下代码: class ResultsPresenter def initialize(project) @project = project end def results results = Rails.cache.fetch("#{@project}/results") do sleep 3
to_param
或cache_key
)到Rails.cache.fetch
,它将创建一个键并缓存块的响应
我有以下代码:
class ResultsPresenter
def initialize(project)
@project = project
end
def results
results = Rails.cache.fetch("#{@project}/results") do
sleep 3
a = long_running_query
b = another_long_query
c = a + b
end
end
end
# called
project = Project.find(params[:project_id]_
presenter = ResultsPresenter.new(project)
presenter.results
@project
已传递给ResultsPresenter
,是一个ActiveRecord模型。当我指定“{@project.to_param}/results”
或“{@project.cache_key}/results”
时,一切正常。我还检查了@project
是否正在更新,但没有更新
有人知道为什么它不采用ActiveRecord模型吗?您希望缓存键是数组,可能是
Rails.cache.fetch([@project,'results'])
这将提供一个缓存键,其行为“project/5-20190812000000/results”
。模型的格式为“处的“model\u name/model\u id-updated\u”,其余数组值与/
连接
如果要查看从示例生成的键,它将类似于“#/results”
。之所以发生这种情况,是因为您正在烘焙@project.to\u s
的值,使之成为传递给fetch
的键的值