我想将表格的id
字段更改为uuid
。
以下是我的代码:
class AddUuidToProjects < ActiveRecord::Migration[5.0]
def up
add_column :projects, :uuid, :string, limit:36, null: false, first: true
add_column :projects, :old_id, :integer
Project.all.each do |p|
p.update!(old_id: p.id)
end
change_table :projects do |t|
t.remove :id
t.rename :uuid, :id
end
execute "ALTER TABLE projects ADD PRIMARY KEY (id);"
Project.all.each do |p|
# has_one image
Image.find(p.old_id).update!(project: p)
# has_many stories
Story.where(project_id: p.old_id).each do |s|
s.update!(project: p)
end
end
end
...
end
当尝试使用t.remove :id
时,此迁移会因外键约束而中断。错误消息如下:
Mysql2::Error: Cannot drop column 'id': needed in a foreign key constraint 'fk_rails_be41fd4bb7' of table 'db_dev.stories': ALTER TABLE `projects` DROP `id`
事实上,如果整个迁移都运行了,那么我将用另一个列替换id列,并修复外键。所以,有没有办法在迁移时忽略约束条件呢?