R – ActiveRecord models cached in rake tasks

activerecordrakeruby-on-rails

I know that in rails 2.3.2 ActiveRecord queries are cached, i.e. you may see something in the development/production log:

CACHE (0.0ms)   SELECT * FROM `users` WHERE `users`.`id` = 1

I was wondering if the same principles apply to rake tasks.

I have a rake task that will query a lot of different models, and I want to know if I should implement my own caching, or if this behavior is included by default.

Also, is there a way to see the sql queries that are performed during the rake task? Similar to that of the development/production log

Best Answer

The SQL cache isn't enabled per default for rake tasks. You can wrap your code in a cache block, like this:

task :foobar => :environment do
  ActiveRecord::Base.connection.cache do
    User.find 1 # Will hit the db
    User.find 1 # Will hit the cache
  end
end

This is essentially what Rails does for controller actions. Note that the cache uses memory and rake tasks has a tendency to work with large sets of data, which might give you issues. You can selectively opt-out of caching for parts of your code, using uncached