Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord models cached in rake tasks?

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

like image 656
gmoniey Avatar asked May 19 '09 00:05

gmoniey


People also ask

Does ActiveRecord cache?

ActiveRecord makes accessing your database easy, but it can also help make it faster by its intelligent use of caching.

What is Rails schema cache?

Rails offers schema cache in these scenarios which can be used to avoid the expensive SHOW FULL FIELDS query. The cache file is nothing but a Rails readable file which contains the schema information. This file can be generated using the rails db:schema:cache:dump command.

What does Rails cache do?

1.1 Page Caching Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the web server (i.e. Apache or NGINX) without having to go through the entire Rails stack. While this is super fast it can't be applied to every situation (such as pages that need authentication).


1 Answers

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

like image 61
troelskn Avatar answered Oct 04 '22 12:10

troelskn