How can I indicate that all tables should contain specific fields?

Suppose I have already defined my database with a large number of tables (about 40). Now I understand that I want to add some columns to each table. For the sake of example, let it be created_by and updated_by .

Is there a way to make this painless without going through 40 migrations and updating each of them manually?

I am using rails 2.3.8

+4
source share
3 answers

You can create one hyphen and put this code into it. It will give you an array of all the tables (minus the "schema_migrations" table that Rails automatically creates) and add the column (s) to each of them.

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

You do not need forty migrants. You can only do 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 
+1
source

This question / answer helped me fix the coding 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 
0
source

Source: https://habr.com/ru/post/1341222/


All Articles