update_all(updates, conditions = nil, options = {}) public

Updates all records with details given if they match a set of conditions supplied, limits and order can also be supplied. 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.

Parameters

  • updates - A string, array, or hash representing the SET part of an SQL statement.

  • conditions - A string, array, or hash representing the WHERE part of an SQL statement. See conditions in the intro.

  • options - Additional options are :limit and :order, see the examples for usage.

Examples

# Update all customers with the given attributes
Customer.update_all :wants_email => true

# Update all books with 'Rails' in their title
Book.update_all "author = 'David'", "title LIKE '%Rails%'"

# Update all avatars migrated more than a week ago
Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]

# Update all books that match conditions, but limit it to 5 ordered by date
Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5

# Conditions from the current relation also works
Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')

# The same idea applies to limit and order
Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
Show source
Register or log in to add new notes.
March 23, 2011
5 thanks

Timestamps

Note that ActiveRecord will not update the timestamp fields (updated_at/updated_on) when using update_all().

December 10, 2010 - (>= v3.0.0)
3 thanks

complex conditions

If you need add complex conditions you can use this:

Model.where(:foo => 'bar').where(:attr => 1).update_all("author = 'David'")
October 1, 2013
1 thank

Update multiple attributes with raw sql

You can update multiple attributes with sql for each record being updated by using the following syntax:

example

Model.update_all("foo = 'bar', baz = 'bat'")
June 17, 2011
1 thank

bug's fixed, though

in 3.1.0. it works in sqlite3 even, via nested query

but 3.0.3, 3.0.7-9 all broken

June 15, 2011
1 thank

bug?

beware, update_all silently ignores :limit and :order option in 3.0.8.

I’ve fixed my code temporarily with

update_all "foo=1 where #{myscope.where_values} limit 1"