This Week in Edge Rails

February 14, 2009 – February 27, 2009

The sharp-eyed will notice that This Week covers two weeks this week. As Rails 2.3 approaches release, the core team is getting pickier about what goes into the source code, and is concentrating on fixing bugs. You can expect to see Rails 2.3 RC2 very soon, and that may be the last release candidate. So if you haven’t tested your own applications on Rails 2.3 yet, it’s time to do so. The edge code is generally stable right now, so it’s a great time to take a look.

Batch Processing

You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using find_in_batches:


Customer.find_in_batches(:conditions => {:active => true}) do |customer_group|
  customer_group.each { |customer| customer.update_account_balance! }
end

You can pass most of the find options into find_in_batches. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the :limit option. Instead, use the :batch_size option, which defaults to 1000, to set the number of records that will be returned in each batch.

The new each method provides a wrapper around find_in_batches that returns individual records, with the find itself being done in batches (of 1000 by default):


Customer.each do |customer|
  customer.update_account_balance!
end

Note that you should only use this method when you have enough records to justify batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop.

commit

A Note About Template Loading

After some extensive work by several authors (here’s the Lighthouse ticket), Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don’t check for a new template file when they’re rendered – but they also mean that you can’t replace a template “on the fly” without restarting the server.

In most cases, you’ll want template caching to be turned on in production, which you can do by making a setting in your production.rb file:


config.action_view.cache_template_loading = true

This line will be generated for you by default in a new Rails 2.3 application. But please note: if you’ve upgraded from an older version of Rails, you won’t have this setting in your production.rb and template caching will be off by default. Unless you really need the ability to update templates in production without restarting the server, you should be sure to add this setting when you upgrade.

blog comments powered by Disqus