Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails jbuilder caching + query

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
like image 211
Tug Avatar asked May 31 '26 09:05

Tug


1 Answers

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.

like image 163
oma Avatar answered Jun 02 '26 23:06

oma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!