Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new column in an existing table in Rails 5?

I want to add a new column in one of my table in Rails 5. I recently renamed a column by using the following way:

rails g migration ChangeJobsTable

then in 20160802104312_change_jobs_table.rb:

class ChangeJobsTable < ActiveRecord::Migration[5.0]
  def change
    rename_column :jobs, :skills, :skills1
  end
end

then

rails db:migrate

It worked fine, but now if I want to also add a new column skills2, do I need to do it like this?

class ChangeJobsTable < ActiveRecord::Migration[5.0]
  def change
    add_column :jobs, :skills2
  end
end
like image 695
Amrinder Singh Avatar asked Aug 02 '16 10:08

Amrinder Singh


People also ask

How do I add a column to an existing table in laravel?

The Laravel migrations will use the Schema facade to create and modify database tables and columns: Schema::create('tasks', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); Inside the facade, you could specify the different columns that you want to add.

How do you add multiple columns in rails?

To add multiple columns to a table, separate field:type pairs with spaces when using rails generate migration command.


2 Answers

You forgot to add datatype, below is the updated migration.

class ChangeJobsTable < ActiveRecord::Migration[5.0]
  def change
    add_column :jobs, :skills2, :string
  end
end
like image 141
hgsongra Avatar answered Oct 07 '22 02:10

hgsongra


You indeed forgot the datatype. You can also do it via the console in the future:

rails g migration AddSkills2ToJobs skills2:string

like image 21
Samy Kacimi Avatar answered Oct 07 '22 02:10

Samy Kacimi