2011-02-24 51 views
4

我已經用很多表格(大約40)定義了我的數據庫。我現在意識到我想爲每個表添加某些列。爲了舉例,讓它爲 created_byupdated_by如何指定所有表格應包含特定字段?

有沒有辦法做到這一點,而不需要經歷40次遷移並手動更新每一個?

我正在使用rails 2.3.8

回答

11

您可以生成單個遷移並將此代碼放入其中。它會給你一個所有表的數組(減去Rails自動創建的「schema_migrations」表),並將列添加到每個表中。

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

這正是我一直在尋找的。 – Calin 2011-02-24 22:03:13

+0

加油!乾淨和容易:) – fl00r 2011-02-24 22:05:21

+0

@Dylan,什麼如果我創建新表,應該添加該列,當我創建新的表自動作爲軌添加「created_at」和「updated_at」 – 2017-01-11 14:32:14

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 
+0

感謝您的快速答覆。儘管如此,我發現其他解決方案更簡單清晰。 – Calin 2011-02-24 22:03:57

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 
相關問題