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

3

12

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
Morava answered 2/8, 2016 at 10:56 Comment(3)
you are on right track....go aheadSteal
i got this error: rails aborted! StandardError: An error has occurred, this and all later migrations canceled: wrong number of arguments (given 2, expected 3..4)Morava
yes, just follow hgsongra(hitesh) instruction..Steal
L
16

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
Liripipe answered 2/8, 2016 at 11:4 Comment(0)
M
18

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

rails g migration AddSkills2ToJobs skills2:string

Malady answered 2/8, 2016 at 13:57 Comment(0)
L
16

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
Liripipe answered 2/8, 2016 at 11:4 Comment(0)
N
1

This worked for me and you can verify after in the schema

rails g migration add_skills2_to_ChangeJobsTable skills2:string

rake db:migrate

Navarino answered 9/1, 2020 at 1:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.