Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 231
Calin Avatar asked Dec 13 '22 15:12

Calin


2 Answers

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
like image 119
Dylan Markow Avatar answered Apr 27 '23 11:04

Dylan Markow


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
like image 43
jemminger Avatar answered Apr 27 '23 12:04

jemminger