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
ActiveRecord makes accessing your database easy, but it can also help make it faster by its intelligent use of caching.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With