Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 当模型作为键给定时,Rails.cache.fetch不工作_Ruby On Rails_Caching - Fatal编程技术网

Ruby on rails 当模型作为键给定时,Rails.cache.fetch不工作

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

我的印象是我们可以给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
      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
的键的值