ruby-on-railscachingjbuilder

Jbuilder Partial Cache not added to output


I'm running a task to build a cache for a large json output using jbuilder. The cache is getting populated and I can output it to the log via puts, but how can I add it to the json file returned by the main jbuilder template?

I'm pre-warming my cache like this:

task update_cache: :environment do
  @jobs = Job.where(archived: false).where(assignee_id: 262).each do |job|
    puts "job: #{job.id}"
    job.workspans.each do |workspan|
      json = ApplicationController.new.render_to_string(
        template: 'api/jobs/_workspan',
        locals: { :workspan => workspan }
      )      
      Rails.cache.write("workspan-#{workspan.id}", json)
    end
  end
end

And fetching it like this

json.jobs @jobs do |job|
  json.job  do
    json.(job, *Job.column_names)
    json.circuit { json.(job.circuit, *Circuit.column_names) }
    json.workspans(job.ordered_workspans) do |workspan|                    
      Rails.cache.fetch("workspan-#{workspan.id}") do
        render json.partial! 'workspan', workspan: workspan
      end
    end
  end
end

The workspans node is returned incorrectly as []


Solution

  • Two changes were required in the task, save as json, not string and change the cache key

    Rails.cache.write("jbuilder/views/workspan-#{workspan.id}", JSON.parse(json_string))
    

    Which then allowed the jBuidler template to fetch and include the cached json in the normal jbuilder name. Note without digest.

    json.cache! "workspan-#{workspan.id}",  skip_digest: true do
       json.partial! 'workspan', workspan: workspan
    end