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

6 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.

  4. Comment from Doug | 17 September 2009 | 6:16 pm :

    Um – I’m still very much a rails and ruby newbie, so how do you invoke/use this “monkey patch” An example would be quite helpful. This patch could save me a ton of time, so any help would be greatly appreciated!

  5. Comment from Stephen Sykes | 17 September 2009 | 7:03 pm :

    Make a file called query_cached_off.rb in the directory config/initializers. Place the code in there. The next time you restart rails the query cache will be turned off.

  6. Comment from Doug | 18 September 2009 | 9:15 pm :

    Stephen,

    That’s awesome – thanks so very much, this saves me a ton of time! And thanks for responding so quickly.

    Doug

Leave your comment...

Powered by WP Hashcash

Blog Archives

Navigation


About this blog

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


Find Something?