如何指定所有表应包含某些字段?

时间:2011-02-24 21:43:30

标签: ruby-on-rails rails-migrations

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

有没有办法在没有经过40次迁移的情况下轻松完成这项任务并手动更新每一次?

我正在使用rails 2.3.8

3 个答案:

答案 0 :(得分:11)

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

tables = ActiveRecord::Base.connection.tables - ["schema_migrations"]
tables.each do |table|
  add_column table, :created_by, :integer
end

答案 1 :(得分: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

答案 2 :(得分: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