Demosophy Demosophy - 8 months ago 50
Ruby Question

Does rails perform SQL Caching for Actions not involving controller?

The rails documentation says that SQL caching is performed for every action. However I'm not clear what "every action" means. Are there any types of processes in the standard rails toolbox which are exempt from caching?

For instance, would an ActiveJob benefit from SQL Caching? What about Rake tasks?


Run rack middleware and you'll see use ActiveRecord::QueryCache - this is the middleware responsible for caching your queries during request.

This method is run when action is started and this method - when action has completed.

Interesting method is this one - it calls query cache module to perform all the caching. Docs are here.

My guess would be that you can use this module inside any method you'd like - background jobs, rake tasks etc. This module is included in activerecord by default, so to enable query cache run at the start of task/method:


and when method/task is finished, execute these two methods:


N.B. Remember to disable the query cache - otherwise the caching would be performed where you may not want it. Also perform profiling and use this cache only where you know it woun't cause side effects. And one more thing: this is a singleton method - when you enable this cache, it's enabled for the entire process.