How to disable the query cache in rails 2.1

If you need to disable the query cache in rails, it’s not particularly easy to do that.
There is some discussion about it (dated March 2008) here.
Although you can turn all caching off, and you can turn the query cache off explicitly in your code using uncached, there isn’t a way to turn just the query cache off globally at configuration time.

So, then, here’s the monkey patch you need (tested on Rails 2.1.1). Although this is not particularly optimal (in that some query caching related code is still called), it will work.  You can put this at the bottom of your environment.rb somewhere, or even better put it in its own file in the initializers directory (e.g. query_cached_off.rb).

module ActiveRecord
  module ConnectionAdapters
    module QueryCache
      private
      def cache_sql(sql)
        yield
      end
    end
  end
end

3 comments for this post.

  1. Comment from Morgan Roderick | 1 October 2008 | 1:06 pm :

    Thanks for sharing!

    Very useful monkey patch for developement :)

  2. Comment from Luke Francl | 1 October 2008 | 3:12 pm :

    I recently had to figure out how to disable the query cache, but just for one method, so I used uncached. I wrote up that little article about how to do that in case anybody Googled it (thanks for the link!)

    Just curious — why do you need to disable query caching entirely?

  3. Comment from Stephen Sykes | 2 October 2008 | 8:03 am :

    I needed to disable query caching to do some testing with my slim-attributes gem ( http://slim-attributes.rubyforge.org/ ).

    Conceivably your memory footprint could end up being smaller if you turn off query caching. Probably marginal though.

Leave your comment...

Powered by WP Hashcash

Blog Archives

Navigation


About this blog

A blog about Ruby, Rails and other tech. Mostly.


Find Something?