Update multiple records at once with Active Record

Have you ever found that you needed to update more than one record at a time? Rails has an elegant solution for this:


Updates all records in the current relation with details given. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations. However, values passed to update_all will still go through Active Record’s normal type casting and serialization.

Say you are working with a library book tracking system. One user has returned three books today.

# user with id 100 checked out books:
> [
   #<Book id:1, title: 'The Hobbit', status: 'checked_out', user_id: 100>, 
   #<Book id:2, title: 'Children of Time', status: 'checked_out', user_id: 100>,
   #<Book id:3, title: 'The Count of Monte Cristo', status: 'checked_out', user_id: 100>

You could update each record individually using the commonly used update active record function, however rails also provides the update_all function:

checked_out_books = User.find(100).books.checked_out
checked_out_books.update_all(status: 'returned')

Which is great! We have successfully marked the books in the system as returned with one call to the database (instead of 3)!

Some things to consider when using this method:

  • this method does not trigger model callbacks
  • this method does not update the updated_at field automatically. However you can manually pass the current DateTime to updated_at.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s