如何重命名列并同时通过迁移更改其类型 [英] How to rename a column and change its type by migration same time
问题描述
在我的 general_exams
表中,有一列名为 semester
,类型为 string
.现在我想把它的名字改成semester_id
,类型是integer
.我已经阅读了关于迁移的内容,并且它有可用的转换:
In my general_exams
table, I have a column named semester
, type is string
. Now I want to change its name to semester_id
, type is integer
. I have read about migration and it has available transformations:
- rename_column(table_name, column_name, new_column_name):重命名列但保留类型和内容.
- change_column(table_name, column_name, type, options):使用与 add_column 相同的参数将列更改为不同的类型.
所以,我像这样创建我的迁移文件:
So, I create my migration file like this:
class RenameSemesterFromGeneralExams < ActiveRecord::Migration
def change
rename_column :general_exams, :semester, :semester_id
change_column :general_exams, :semester_id, :integer
end
end
但是,当我运行 rake db:migrate
时,它有错误:
But, when I run rake db:migrate
, it has error:
== RenameSemesterFromGeneralExams: migrating =================================
-- rename_column(:general_exams, :semester, :semester_id)
-> 0.0572s
-- change_column(:general_exams, :semester_id, :integer)
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::Error: ERROR: column "semester_id" cannot be cast to type integer
: ALTER TABLE "general_exams" ALTER COLUMN "semester_id" TYPE integer
在我的表 GeneralExam 中,我销毁了所有数据.那么,任何人都可以告诉我我该怎么做?或者我必须创建两个迁移文件?
In my table GeneralExam, I destroyed all data. So, anyone can tell me how can I do that? Or I must create two migration files?
推荐答案
您的问题可能是 semester
包含无法转换为 integers
的数据.这就是您收到强制转换错误的原因.
Your problem is probably that the semester
contains data that cannot be converted to integers
. That's why you get a cast error.
我怀疑您需要做更多的工作来完成这项工作,因为唯一想到的是删除列并创建一个具有正确值的新列.
I suspect you need to do more work to make this work as the only thing that comes to mind is removing the column and creating a new one with the correct values.
但是您可以简单地在一次迁移中先 remove_column 和 add_column .这应该可以完美运行.
But you can simply remove_column and then add_column in one migration. That should work flawlessly.
我还建议您先只添加_column,然后进行映射过程,将旧的 semester
值映射到新的 semester_id
,然后删除该列.
I'd also suggest you only add_column first, then do the mapping process where you map the old semester
value onto the new semester_id
and then drop the column.
请记住,您可以在迁移中执行 ActiveRecord 操作.所以你可以把代码放在那里.
Keep in mind that you can do ActiveRecord manipulations inside your migration. So you can put that code in there.
这篇关于如何重命名列并同时通过迁移更改其类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!