Question

My Ruby_2+Rails_4+Postgres_9.2 app contains tens of models. A recent CR requires me to add two new fields to ALL of my models. I know I can painstakingly create a migration which will individually 'add_column' to each of my models. Is there any easier way of doing the same where I wouldn't need to do that?

Was it helpful?

Solution

def self.up
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == "schema_migrations"
    add_column table, :column_name, :column_type
  end
end

EDIT:(getting table name from models)

 def self.up
    Rails.application.eager_load!
    ActiveRecord::Base.descendants.each do |model|
      add_column model.table_name, :column_name, :column_type
    end
 end

OTHER TIPS

def tables
  (ActiveRecord::Base.connection.execute 
    "SELECT table_name FROM INFORMATION_SCHEMA.TABLES 
       WHERE table_schema = '#{ActiveRecord::Base.connection.current_database}' 
       AND table_type = 'BASE TABLE'").to_a.flatten
end

def self.up
  tables.each do |table| 
    add_column table, :a_column1, :a_type
    add_column table, :a_column2, :a_type
  end
end

Add a migration and loop through all the tables:

def self.up
  [:table_name1, :table_name2, :table_name3, ...].each do |table_name| 
     add_column table_name, :column1, :string
     add_column table_name, :column2, :string
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top