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


Parameters

oupdates - 写需要重新设置的一个string,array或者hash

oconditions - 条件

ooptions - 额外的条件 :limit 和 :order, 看下边例子



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


复杂的条件查询:

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



Timestamps

当update_all的时候不会update Timestamps字段((updated_at/updated_on) )



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




例子:


class UpdatePaaaData < ActiveRecord::Migration

def self.up

Paaa.update_all(["parent_id = ?", 1],

["action = ?", '/aaa/bbb'])

end


def self.down

end

end

然后执行rake:db:migrate


ok