3

Just after some advice on how I can cache both a jbuilder view and an activerecord query. The way I'm doing it currently doesn't feel right, as I'm essentially storing two things in the cache. Can I combine this somehow? I need to cache the SQL record so the database doesn't get hit and also the view file to maximise speed.

# Controller
@posts = Rails.cache.fetch ["posts"], :expires_in => 1.hour do
  Post.all.limit(10).order("id desc").to_a
end

and

# Jbuilder view
json.cache! ["posts"], :expires_in => 1.hour do |json|
    json.array! @posts do |post|
      json.id post.id
      json.title post.title
    end
 end
Tug
  • 41
  • 1
  • 5

1 Answers1

2

I think you're overthinking this, unless that activerecord query is really slow. The caching mechanism is really smart and will pull your objects to check the updated_at. If updated, build the json response. If not, serve the previously built. Often that can take a 2sec job down to 10ms, or to whatever time your initial db query takes.

However, if you insist, this answer shows a way. https://stackoverflow.com/a/23783119/252799 Notice that the activerecord call is within the cache block, so it would only be executed if there is a cache miss.

Community
  • 1
  • 1
oma
  • 38,642
  • 11
  • 71
  • 99
  • Seems like any activerecord query is going to be really slow compared to any view rendering that needs to be done, no? – nroose Jun 22 '22 at 20:51