Mir*_*318 3 mysql ruby-on-rails foreign-keys rails-migrations ruby-on-rails-5
我正在尝试将表的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
Run Code Online (Sandbox Code Playgroud)
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`
Run Code Online (Sandbox Code Playgroud)
问题是,如果整个迁移运行,那么我将将该id列替换为另一列,并修复外键。那么,有没有办法可以忽略迁移的限制呢?
Art*_*jev 10
Project.connection.disable_referential_integrity do
Project.delete_all # An example
end
Run Code Online (Sandbox Code Playgroud)
ActiveRecord::Base.connection.disable_referential_integrity。
轨道 4.2+。
| 归档时间: |
|
| 查看次数: |
5766 次 |
| 最近记录: |