Are ActiveRecord models cached in rake tasks?

I know that in Rails 2.3.2 ActiveRecord requests are cached, that is, you can 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 request a lot of different models, and I want to know if I should implement my own caching or if this is enabled by default.

Also, is there a way to see sql queries that run during a rake task? As in the development / production magazine

+5
source share
3 answers

ActiveRecord. Rake-Tasks , , . production. . Rails .

:

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
+2

, .

env :

RAILS_ENV=test

​​ , Rails.

+1

SQL . , :

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, in essence, is what Rails does for controller actions. Note that the cache uses memory, and rake tasks tend to work with large data sets, which may give you problems. You can selectively refuse caching for parts of your code usinguncached

+1
source

All Articles