我正在尝试将表的 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
列换成另一列,并修复外键。那么,有什么办法可以忽略迁移的限制?
最佳答案
ActiveRecord::Base.connection.disable_referential_integrity
(Github)。至少需要 Rails 4.2。
附言
我发现上面评论中的代码很容易出错。对我来说,主要原因是缺乏对如此关键任务的测试。有一个很棒的article来自“Thoughtbot”关于将数据迁移与结构迁移混合的其他问题。
我会考虑创建单独的数据迁移(当然包括测试)。
关于mysql - Rails 迁移——暂时忽略外键约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005849/