class method self.update_all

Ruby on Rails 2.3.18

Since v2.2.3 Last seen in v2.3.18

Available in: v2.2.3 v2.3.18

Signature

self.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.

Parameters

  • updates - A string of column and value pairs that will be set on any records that match conditions. This creates the SET clause of the generated SQL.

  • conditions - An SQL fragment like “administrator = 1” or [ “user_name = ?”, username ]. See conditions in the intro for more info.

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

Examples

# Update all billing objects with the 3 different attributes given
Billing.update_all( "category = 'authorized', approved = 1, author = 'David'" )

# Update records that match our conditions
Billing.update_all( "author = 'David'", "title LIKE '%Rails%'" )

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

Parameters

updates req
conditions opt = nil
options opt = {}
Source
# File activerecord/lib/active_record/base.rb, line 831
      def update_all(updates, conditions = nil, options = {})
        sql  = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} "

        scope = scope(:find)

        select_sql = ""
        add_conditions!(select_sql, conditions, scope)

        if options.has_key?(:limit) || (scope && scope[:limit])
          # Only take order from scope if limit is also provided by scope, this
          # is useful for updating a has_many association with a limit.
          add_order!(select_sql, options[:order], scope)

          add_limit!(select_sql, options, scope)
          sql.concat(connection.limited_update_conditions(select_sql, quoted_table_name, connection.quote_column_name(primary_key)))
        else
          add_order!(select_sql, options[:order], nil)
          sql.concat(select_sql)
        end

        connection.update(sql, "#{name} Update")
      end

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

Defined in ActiveRecord::Base

Type at least 2 characters to search.

↑↓ navigate · open · esc close