Rails将字符串转换为整数的迁移? [英] Rails Migration to convert string to integer?
问题描述
是否可以将一个字符串的字段更改为整数而不清除已输入的数据?
Is it possible to change a field that's a string to an integer without clearing the data already entered?
当前表的结构是: / p>
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.
感谢,
Danny
推荐答案
不要删除此列,它会清除数据。
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)drop 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将字符串转换为整数的迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!