6
votes

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

3

3 Answers

3
votes

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

2
votes

You are talking about ActiveRecord Query Caching. That should work in Rake-Tasks too, provided you're running them in an environment with caching enabled, e.g. production. See Rails Guide on Caching for examples.

It may or may not be the right sort of caching for your case:

u1=User.find 1  # loads user1 first time from DB
u2=User.find 2  # loads user2 first time from DB
u1again = User.find 1 # loads user1 from cache
all = User.all # loads user1 and user2 from DB again
1
votes

A rake task will run in the the environment you specify, in which case it will adopt the rules of that environment.

You can set the rails env from the command line:

RAILS_ENV=test

Logging can be set as part of rake and you should see this in your normal Rails log.