4

假设我已经用很多表(大约 40 个)定义了我的数据库。我现在意识到我想在每个表中添加某些列。为了这个例子,让它成为 created_byand updated_by

有没有办法在不经历 40 次迁移并手动更新每个迁移的情况下轻松做到这一点?

我正在使用导轨 2.3.8

4

3 回答 3

12

您可以生成一个迁移并将此代码放入其中。它将为您提供所有表的数组(减去 Rails 自动创建的“schema_migrations”表),然后将列添加到每个表中。

tables = ActiveRecord::Base.connection.tables - ["schema_migrations"]
tables.each do |table|
  add_column table, :created_by, :integer
end
于 2011-02-24T21:55:19.093 回答
1

你不需要四十次迁移。您可以只进行一次迁移,例如:

def self.up
  %w(table1 table2 table3).each do |table_name|
    ActiveRecord::Base.connection.execute "ALTER TABLE #{table_name} ADD created_by int, updated_by int"
  end
end
于 2011-02-24T21:53:08.737 回答
0

这个问题/答案帮助我修复了所有表格的编码......

class FixCharacterSet < ActiveRecord::Migration
  def up
    tables = ActiveRecord::Base.connection.tables - ["schema_migrations"]
    tables.each do |table|
        ActiveRecord::Base.connection.execute "ALTER TABLE #{table} CONVERT TO CHARACTER SET utf8 COLLATE 'utf8_general_ci';"
    end
  end

  def down
  end
end
于 2012-07-30T16:31:16.477 回答