Q:

Rails.cache.fetch not working when model given as key

I was under the impression that we could give Rails a model (anything responding to to_param or cache_key) to Rails.cache.fetch and it would create a key and cache the response of the block.
I have this code:
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 was passed to ResultsPresenter and is an ActiveRecord model. When I specify "#{@project.to_param}/results" or "#{@project.cache_key}/results" everything works just fine. I also checked if the @project was being updated but it's not.
Anyone know why it does not take an ActiveRecord model?

A:

You want your cache key to be an array, probably Rails.cache.fetch([@project, 'results']).
This will give a cache key along the lines of "project/5-20190812000000/results". The format for the model is "model_name/model_id-updated_at" with the rest of the array values joined with /.
If you were to look at the key generated from your example, it would look something like "#<Project:0x007fbceaadbbc90>/results". This is happening because you are baking the value of @project.to_s into the value of the key you are passing into fetch.

