开发者

Migrations: change column from integer to string

Can anyone show me how to edit the following migratio开发者_开发问答n 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!


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

change_column :contact_infos, :phone, :string


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.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜