简体   繁体   中英

How can I specify that all tables should contain certain fields?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM