views:

16

answers:

1

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?

+1  A: 

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 memorization, 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

Elad Meidar
I needed @@class_variables, but, other than that, exactly what I was looking for. Thanks.
Christopher Foy