更新一列,所有行

我在表中添加了一个新列,但是忘记添加 :default选项。现在我要在每一行上填充该列。

使用控制台有什么办法吗?我已经在谷歌上搜索了一个小时,但是什么都找不到。

我知道如何对单个对象执行此操作,但不知道如何对模型的所有行执行此操作。

Foo.find(1).update_attribute(:myattribute, 'value')
45648 次浏览

Try this:

Foo.update_all(some_column: "bar")

This will generate SQL query to database:

UPDATE "foos" SET "some_column" = "bar";

Since you already created the new field in a previous migration, create a brand new migration:

rails g migration UpdateFoos

Modify the migration:

def self.up
say_with_time "Updating foos..." do
Foo.find(:all).each do |f|
f.update_attribute :myattribute, 'value'
end
end
end


# from command line
Rake db:migrate

Let me know if this works, it might need a few adjustments. See rails docs for more:

you can do like this:

Foo.update_all(new_column: "bar")

Of course you can use smth like Foo.update_all(:myattribute => "value"), but it'll modify only already created data. To set default value for all "future" data it's a good way to create a separate migration like this:

rails generate migration AddDefaultValueToFoo

Modify new migration (for ex. myattribute has a string type) like this:

class AddDefaultValueToFoo < ActiveRecord::Migration
def self.up
change_column :foos, :myattribute, :string, :default => "value"
Foo.update_all(:myattribute => "value")
end
end