instance method update_all

Ruby on Rails 3.2.22.5

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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

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')

Parameters

updates req
conditions opt = nil
options opt = {}
Source
# File activerecord/lib/active_record/relation.rb, line 274
    def update_all(updates, conditions = nil, options = {})
      IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled?
      if conditions || options.present?
        where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
      else
        stmt = Arel::UpdateManager.new(arel.engine)

        stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
        stmt.table(table)
        stmt.key = table[primary_key]

        if joins_values.any?
          @klass.connection.join_to_update(stmt, arel)
        else
          stmt.take(arel.limit)
          stmt.order(*arel.orders)
          stmt.wheres = arel.constraints
        end

        @klass.connection.update stmt, 'SQL', bind_values
      end
    end

Defined in activerecord/lib/active_record/relation.rb line 274 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Relation

Type at least 2 characters to search.

Use the arrow keys to navigate results, Enter to open one, Escape to close.

Keyboard shortcuts

/
Focus search
⌘K / Ctrl-K
Command palette
?
This help
Esc
Close