且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

由于外键约束,无法删除对象

更新时间:2022-02-24 08:58:44

需要先删除引用用户的身份。然后,您可以删除用户。默认情况下,外键执行 restrict ,因此,如果有任何引用,则不能删除该用户。

You would need to remove the Identity that references the user first. Then you can delete the user.. By default the foreign key is doing a restrict so you cannot delete the user if anything references to it.

如果您想使用Rails处理破坏身份的行为,则可以

if you would like use Rails to handle destroying the identity you can do

class User < ActiveRecord::Base
  has_many :identities,  dependent: :destroy 

  ......

 end 

这会导致Rails销毁所有相关记录。

Which would cause Rails to destroy all the dependent records.

但是在使用外键时,您可以调整迁移以设置级联删除

But as you are using Foreign keys, you can adjust your migration to set cascade deletes

 add_foreign_key :identities, :users, on_delete: :cascade

假设rails 4.2其中有本地支持

Assuming rails 4.2 which has native support