Demosophy Demosophy - 3 months ago 15
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?

Answer

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:

ActiveRecord::Base.connection.enable_query_cache!

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

ActiveRecord::Base.connection.clear_query_cache
ActiveRecord::Base.connection.disable_query_cache!

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.

Comments