35

I know how to add one column to an existing table. Now I have to add many columns to an existing table. Is there a shorter way for:

add_col1_col2_col3_col4_.._coln_to_tables col1:integer col2:integer etc...

Do I have to do the above for ALL the additional columns I have to add?

Flip
  • 6,233
  • 7
  • 46
  • 75
Sylar
  • 11,422
  • 25
  • 93
  • 166

6 Answers6

64

No not necessary. You can do

Assuming TableName is user

rails g migration AddColumnsToUser col1:integer col2:integer .. etc.
Shweta
  • 1,171
  • 7
  • 11
21

Here's a good resource on ActiveRecord:Migrations which lists all the commands you can use to manipulate your databases. You can also do the task this way:

rails g migration AddMoreColumnsToModel

Then open the migration file and put:

def change
  add_column :table, :new_column, :type
  # add as many columns as you need 
end

If you wanted to do what Maxd suggests, having literally 100 columns of the same type auto-create, his code is a good idea.

Proto
  • 764
  • 1
  • 7
  • 22
11

Just create migration and generate these columns i.e.:

class ChangeTables < ActiveRecord::Migration
  def change
    change_table :tables do |t|
      100.times do |i|
        t.integer :"column_#{i}"
      end
    end
  end
end
Maxim
  • 9,701
  • 5
  • 60
  • 108
3

Similar to above answers but for understanding purpose hope below naming convention is good.

rails g migration add_first_column_and_second_column_to_model first_column:string second_column:string
Dinesh Pallapa
  • 1,172
  • 18
  • 20
1

This migration file can be done in a loop. But do you really want to do this? It does not look correct to create such a heavy model to hold everything.

IcyBright
  • 654
  • 4
  • 15
0

command to create new model and table with columns:

rails g model ModelName col_name1:string col_name2:integer col_name3:text ...

command to add more columns under existing table:

rails g migration AddColumnToModelName col_name4:string col_name5:integer ...

At last, run migration by command:

rake db:migrate
puneet18
  • 4,341
  • 2
  • 21
  • 27