How to use ActiveRecord query cache with custom SQL

In the statistical part of a Rails application, I have some custom SQL calls called with ActiveRecord :: Base.execute () from the model code. They return various units.

Some of these (identical) requests are executed in a loop in the controller, and it seems that they are not cached by the ActiveRecord request cache.

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

+6
ruby-on-rails activerecord query-cache
source share
1 answer

Not sure if AR supports query caching for #execute, you might want to dig out the documentation. Anyway, what you can do is use memorization, which means that you save the results manually until the end of the current query.

do something like this in your model:

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

this will basically only start the request for the first time, and then save the response to @rs until the entire request is completed.

If I'm not mistaken, Rails 2.x already has a macro called memoization in ActiveRecord that does all this automatically

hope this helps

+5
source share

All Articles