Rails ActiveRecord - Batch Updates

Programming in Ruby tutorials and examples

Rails ActiveRecord - Batch Updates

MaxCDN Content Delivery Network

I am currently writing an application that requires a high level of performace. This means that every line of code written has to be scrutinised and performace tested. I am finding myself needing to take a different approach for the simplist of code in order to squeeze out every last drop of speed.

Imagine you need to update an attribute on a collection of items.

  Tag.where(:is_featured => true).each do |tag|
    tag.update_attribute(:is_featured, false)

This is bad for a few of reasons. Firstly we have to load each record into memory and secondly a seperate update statement is fired for every record updated. If there are lots of records your application will feel the performance hit.

If you want to do this in one single sql call it can be done using the update_all method.

  Tag.update_all({ :is_featured => false }, {:is_featured => true })

The first argument are the attributes to update and the second is the filter conditions for the query. So for the case in hand the sql generated will be.

  UPDATE `tags` SET `is_featured` = 0 WHERE `tags`.`is_featured` = 1

The only drawback to this is that you model callbacks will not be triggered, but luckily in my case this is not an issue.