Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ActiveRecord Query Cache with Custom SQL

In a stats part of a Rails app, I have some custom SQL calls that are called with ActiveRecord::Base.execute() from the model code. They return various aggregates.

Some of these (identical) queries are run in a loop in the controller, and it seems that they aren't cached by the ActiveRecord query cache.

Is there any way to cache custom SQL queries within a single request?

like image 519
Christopher Foy Avatar asked Oct 13 '10 20:10

Christopher Foy


1 Answers

Not sure if AR supports query caching for #execute, you might want to dig in the documentation. Anyway, what you can do, is to use memoization, which means that you'll keep the results manually until the current request is over.

do something like this in your model:

def repeating_method_with_execute
   @rs ||= ActiveRecord::Base.execute(...)
end

This will basically run the query only on the first time and then save the response to @rs until the entire request is over.

If I am not wrong, Rails 2.x already has a macro named memoization on ActiveRecord that does all that automatically

hope it helps

like image 153
Elad Meidar Avatar answered Oct 14 '22 00:10

Elad Meidar