17

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!

4 Answers 4

33

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

change_column :contact_infos, :phone, :string
Sign up to request clarification or add additional context in comments.

1 Comment

Should be :string, not :text which is meant for text over 255 chars, unless you plan on storing really long phone numbers.
4

For a reversible migration, use:

def up
  change_column :contact_infos, :phone, :string
end

def down
  change_column :contact_infos, :phone, :integer, using: "phone::integer"
end

Comments

3

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.

Comments

0

Convert column type string into integer in rails migration :

def change
  change_column :contact_infos, :phone, :integer, using: 'phone::integer'
end

Convert column type integer into string in rails migration:

 def change
   change_column :contact_infos, :phone, :string, using: 'phone::string'
 end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.