In a stats part of a Rails app, I have some custom SQL calls that are called with开发者_Go百科 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?
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
精彩评论