Ruby-on-rails 更新一列,所有行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4512696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update a column, all rows
提问by Martin Petrov
I added a new column to my table but I forgot to add the :default option. Now I want to populate that column on every single row.
我在表中添加了一个新列,但忘记添加 :default 选项。现在我想在每一行上填充该列。
Is there a way to do with using the console? I've been searching google for the past hour but I can't find anything.
有没有办法使用控制台?过去一个小时我一直在搜索谷歌,但我找不到任何东西。
I know how to do it for a single object, but not for all in a model. Foo.find(1).update_attribute(:myattribute, 'value')
我知道如何为单个对象执行此操作,但不知道如何为模型中的所有对象执行此操作。Foo.find(1).update_attribute(:myattribute, 'value')
回答by Jimmy Huang
Try this:
尝试这个:
Foo.update_all(some_column: "bar")
This will generate SQL query to database:
这将生成对数据库的 SQL 查询:
UPDATE "foos" SET "some_column" = "bar";
回答by stephenmurdoch
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 docsfor more:
让我知道这是否有效,它可能需要一些调整。有关更多信息,请参阅 rails文档:
回答by jiahut
you can do like this:
你可以这样做:
Foo.update_all(new_column: "bar")
Foo.update_all(new_column: "bar")
回答by wiseland
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:
当然你可以使用 smth like Foo.update_all(:myattribute => "value"),但它只会修改已经创建的数据。要为所有“未来”数据设置默认值,这是创建单独迁移的好方法,如下所示:
rails generate migration AddDefaultValueToFoo
Modify new migration (for ex. myattribute has a string type) like this:
像这样修改新的迁移(例如 myattribute 有一个字符串类型):
class AddDefaultValueToFoo < ActiveRecord::Migration
def self.up
change_column :foos, :myattribute, :string, :default => "value"
Foo.update_all(:myattribute => "value")
end
end

