Sylar
Sylar

Reputation: 12072

Rails 4: Add Multiple Columns to Existing Table

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?

Upvotes: 36

Views: 40093

Answers (6)

puneet18
puneet18

Reputation: 4427

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

Upvotes: 0

Dinesh Pallapa
Dinesh Pallapa

Reputation: 1212

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

Upvotes: 3

Proto
Proto

Reputation: 774

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.

Upvotes: 21

IcyBright
IcyBright

Reputation: 664

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.

Upvotes: 1

Shweta
Shweta

Reputation: 1171

No not necessary. You can do

Assuming TableName is user

rails g migration AddColumnsToUser col1:integer col2:integer .. etc.

Upvotes: 64

Maxim
Maxim

Reputation: 9961

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

Upvotes: 12

Related Questions