Ruby-on-rails Rails Migration 将字符串转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3537064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Migration to convert string to integer?
提问by dannymcc
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
Is this possible using migrations?
这可以使用迁移吗?
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.
我想也许在迁移中删除旧字段,创建一个整数的新字段 - 但我担心这会清除所有已经输入的数据。
Thanks,
谢谢,
Danny
丹尼
回答by user3402754
Don't drop the column, use this
不要删除列,使用这个
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
The "hint" you got from PostgreSQL basically tells you that you need to confirm you want this to happen, and how data should be converted. To confirm the changes, use the block above in your migration
你从 PostgreSQL 得到的“提示”基本上告诉你你需要确认你希望这种情况发生,以及应该如何转换数据。要确认更改,请在迁移中使用上面的块
回答by Jo?o Souza
The other answers are correct, yet you can take one step further with the :usingkeyword:
其他答案是正确的,但您可以使用:using关键字更进一步:
change_column :people, :company_id, :integer, using: 'company_id::integer'
回答by Zaki
Do not drop the column, it will clear the data.
不要删除列,它会清除数据。
You can however try
不过你可以试试
change_column :people, :company_id, :integer
and if all values in company_idcan be converted to integer, it should be fine.
如果中的所有值company_id都可以转换为integer,应该没问题。
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_idin there after some conversion. 2) drop company_id then rename the new column.
如果不是这种情况(即默认情况下并非所有字符串都可以转换),那么您可以分两步完成:1)创建一个新列,然后company_id在进行一些转换后将其加载到其中。2) 删除 company_id 然后重命名新列。
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.
您应该小心使用这两种方法(对于第二种方法更是如此),如果可以的话,您可能应该首先在数据库的副本上执行此操作。

