迁移一行中的许多表?

时间:2018-04-17 08:29:28

标签: ruby-on-rails migration

我的问题是现在我必须删除数据库中几乎表中存在的1列。 我可以通过基本迁移来处理它:

remove_column :table_1, :field_should_removed
remove_column :table_2, :field_should_removed
...
remove_column :table_n, :field_should_removed

但是,有没有办法把所有这些表放在一句话中,如:

remove_column %i[table_1, table_2, ..., table_n], :field_should_removed

1 个答案:

答案 0 :(得分:0)

使用更少的代码执行此操作的方法可以是:

tables = %i[table_1, table_2, ..., table_n]
tables.each do |table|
  remove_column table, :field_should_removed
end

正如你所提到的那样,在大多数表格中你也可以这样做:

ActiveRecord::Base.connection.tables.each do |table|
  table_name = table.to_sym
  if column_exists?(table_name, :field_should_removed)
    remove_column table, :field_should_removed
  end
end
相关问题