Skip to content

Things I’d forgotten: The ActiveRecord update_all method

By Paul Leader

This is the first of a series of short posts on little features in Rails that are occasionally useful, but easily forgotten.

Sometimes it’s easy to forget that Rails’ ActiveRecord is built on relational databases and fall into the trap of doing things with comparatively complex bits of Ruby when they could be done in one go in SQL, more easily, and faster.

One example is ActiveRecord#update_all, which updates all records for a model in one go. You specify the update, the conditions that the record must match, and other SQL options.

An example:

# Update records that match our conditions but limit it to 5 ordered by date
Billing.update_all( "author = 'David'",
                    "title LIKE '%Rails%'",
                    :order => 'created_at', :limit => 5 )

So next time you are farting around writing pointless bits of Ruby to update lots of records, you probably want to reach for update_all instead.