由于外键约束,无法删除对象 [英] can't delete object due to foreign key constraint
问题描述
尝试做一个简单的 user.destroy
,但遇到以下错误:
Trying to do a simple user.destroy
but running into the following error:
错误:表用户上的更新或删除违反了表身份上的外键约束 fk_rails_5373344100
详细信息:仍然从表身份中引用键(id)=(2)。
这是我的身份迁移
class CreateIdentities < ActiveRecord::Migration
def change
create_table :identities do |t|
t.references :user, index: true, foreign_key: true
t.string :provider
t.string :uid
t.timestamps null: false
end
end
end
这是我的用户和身份模型:
Here is my user and identity model:
class Identity < ActiveRecord::Base
belongs_to :user
validates_presence_of :uid, :provider
validates_uniqueness_of :uid, :scope => :provider
def self.find_for_oauth(auth)
find_or_create_by(uid: auth.uid, provider: auth.provider)
end
end
和用户:
class User < ActiveRecord::Base
TEMP_EMAIL_PREFIX = 'ricky@writeit.com'
TEMP_EMAIL_REGEX = /\ricky@writeit.com/
# Include default devise modules. Others available are:
# :lockable, :timeoutable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
validates_format_of :email, :without => TEMP_EMAIL_REGEX, on: :update
...
end
对于外键和引用是新手,所以我完全不确定如何解决此问题。
Im new to foreign keys and references, so I'm not sure at all how to fix this. Any help would be greatly appreciated.
谢谢
推荐答案
需要先删除引用用户的身份。然后,您可以删除用户。默认情况下,外键执行 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
这篇关于由于外键约束,无法删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!