instance method
update_all
Ruby on Rails 3.2.22.5
Since v3.0.20Signature
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:limitand: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
-
updatesreq -
conditionsopt = nil -
optionsopt = {}
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