Rails Migration将字符串转换为整数? [英] Rails Migration to convert string to integer?

查看:33
本文介绍了Rails Migration将字符串转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将字符串字段更改为整数而不清除已输入的数据?

Is it possible to change a field that's a string to an integer without clearing the data already entered?

相关表的当前数据库结构是:

The current db structure for the table in question is:

create_table :people do |t|
t.string :company_id

这可以使用迁移吗?

我在想也许在迁移中删除旧字段,创建一个整数的新字段 - 但我担心这会清除所有已输入的数据.

I'm thinking maybe in the migration drop the old field, create a new one that's an integer - but I'm worried this will clear all of the data already entered.

谢谢,

丹尼

推荐答案

不要丢列,会清空数据.

Do not drop the column, it will clear the data.

你可以试试

change_column :people, :company_id, :integer

如果company_id中的所有值都可以转换成integer,应该没问题.

and if all values in company_id can be converted to integer, it should be fine.

如果不是这样(即默认情况下并非所有字符串都可以转换),那么您可以分两步进行:1)创建一个新列,然后在其中加载company_id经过一些转换.2) 删除 company_id 然后重命名新列.

If that is not the case (ie not all string can be converted by default), then you can do it in two steps: 1) create a new column, then load the company_id in there after some conversion. 2) drop company_id then rename the new column.

您应该小心使用这两种方法(对于第二种方法更是如此),如果可以的话,您可能应该首先在数据库副本上执行此操作.

You should be careful with both methods (more so for the second one) and you should probably do it first on a copy of the database, if you can.

这篇关于Rails Migration将字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆