Rails 4:如何在应用程序中的所有模型中添加列?

时间:2014-01-13 14:50:13

标签: ruby-on-rails ruby-on-rails-4 rails-migrations

我的Ruby_2 + Rails_4 + Postgres_9.2应用程序包含数十个模型。最近的CR要求我为我的所有模型添加两个新字段。我知道我可以煞费苦心地创建一个迁移,它将为每个模型单独添加“add_column”。在我不需要这样做的地方有没有更简单的方法呢?

3 个答案:

答案 0 :(得分:2)

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

编辑:(从模型中获取表名)

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

添加迁移并循环遍历所有表:

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