Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrations: change column from integer to string

Can anyone show me how to edit the following migration to change :phone integer to string?

class CreateContactInfos < ActiveRecord::Migration
  def change
    create_table :contact_infos do |t|
      t.integer :phone
      t.string :facebook
      t.references :user

      t.timestamps 
    end
    add_index :contact_infos, :user_id
  end
end

Thanks in advance!

like image 247
imjp Avatar asked Jul 26 '11 17:07

imjp


2 Answers

I guess you already migrated the one you're showing, so create another in which you'd put:

change_column :contact_infos, :phone, :string
like image 117
apneadiving Avatar answered Oct 22 '22 15:10

apneadiving


I have added some more explanation to this.We need to generate a new migration

rails g migration change_phone_to_be_string_in_contact_infos

If we open up the migration we should see something like this

class ChangePhoneToBeStringInContactInfos < ActiveRecord::Migration[5.0]
 def change
 end
end

What we call this migration will have no impact on what we need to do next, but future we and other developers will thank us for naming our migration appropriately.

As you can see the change method is sitting empty. We need to manually add some code here.

class ChangePhoneToBeStringInContactInfos < ActiveRecord::Migration[5.0]
 def change
  change_column :customers, :phone, :string
 end
end

After Saving this file just do rake db:migrate we can see changes we want.

like image 33
Mritunjay Upadhyay Avatar answered Oct 22 '22 14:10

Mritunjay Upadhyay