How to use ActiveRecord Query Cache with Custom SQL
Asked Answered
I

1

6

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?

Ilk answered 13/10, 2010 at 20:34 Comment(0)
R
5

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

Rescissory answered 14/10, 2010 at 11:31 Comment(1)
I needed @@class_variables, but, other than that, exactly what I was looking for. Thanks.Ilk

© 2022 - 2024 — McMap. All rights reserved.