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

发布于 2024-10-19 06:13:37 字数 187 浏览 1 评论 0原文

假设我已经用很多表(大约 40 个)定义了我的数据库。我现在意识到我想向每个表添加某些列。为了举例,就这样吧 created_byupdated_by

有没有什么方法可以轻松完成此操作,而无需进行 40 次迁移并手动更新每个迁移?

我正在使用 Rails 2.3.8

Supose that I already have defined my database with a lot of tables (around 40). I realize now that I want to add certain columns to each table. For the sake of the example let it be
created_by and updated_by.

Is there any way to do this painless without going through 40 migrations and update each of them manually?

I am using rails 2.3.8

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

溇涏 2024-10-26 06:13:37

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

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

You could generate a single migration and put this code in it. It will give you an array of all the tables (minus the "schema_migrations" table that Rails automatically creates) and than add the column(s) to each one.

tables = ActiveRecord::Base.connection.tables - ["schema_migrations"]
tables.each do |table|
  add_column table, :created_by, :integer
end
‘画卷フ 2024-10-26 06:13:37

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

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

You don't need forty migrations. You can make just one migration, for example:

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
吾性傲以野 2024-10-26 06:13:37

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

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

This question/answer helped me to fix encoding of all tables...

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文