Rails jbuilder caching + query

3.7k Views Asked by At

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
1

There are 1 best solutions below

1
On

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.