Topic: Caching Queries

I'm looking for a way to cache a series of db queries across different requests.

The queries basically determine the content of a sidebar which is visible throughout the whole app and it seems very inefficient to be querying the same data over and over.

Re: Caching Queries

Does the view change at all? You may want to look into fragment caching instead. That will cache it at a higher level which will give better performance.

If you just want to cache the query, you can look into memcache with cache_fu or something.

Railscasts - Free Ruby on Rails Screencasts

Re: Caching Queries

The view does change depending on what page or section is active. I may need to work memcached into the equation.

Re: Caching Queries

I'm unsure if this is an optimal solution, but this is what I have in my models when I want to cache a query:

class Something < ActiveRecord::Base
  cattr_accessor            :cached_sql_query
  after_save                { Something.reset_cached_sql_query }

  def self.cached_sql_query
    @cached_sql_query ||= find(:all, :include ... blah, blah)
  end

  def self.reset_cached_sql_query
    @cached_sql_query = nil
  end
end

Last edited by aleco (2007-08-31 12:19:56)

Re: Caching Queries

Thats an interesting bit of hackery there aleco. Gonna give it a try this week