错误:删除表违反外键约束。仍然从表中引用键ID(许多) [英] ERROR: delete on table violates foreign key constraint. Key id is still referenced from table (many)
问题描述
我正在与Rails和PostgreSQL一起使用,并且保持着一对多的基本关系,一个 Auction
具有许多 Bid s。但是,当我尝试删除拍卖(具有出价)时,出现以下错误:
I'm working with Rails and PostgreSQL and have a basic one-to-many relationship going on, one Auction
has many Bid
s. However when I try and delete an auction (that has bids present) I get the following error:
错误:更新或删除表拍卖违反了表出价上的外键
约束 fk_rails_43e9021cbf。详细信息:Key(id)=(1)
仍从表 bids中引用。
ERROR: update or delete on table "auctions" violates foreign key constraint "fk_rails_43e9021cbf" on table "bids". DETAIL: Key(id)=(1) is still referenced from table "bids".
删除没有出价没有错误。
Deleting auctions with no bids gives no error.
让我感到困惑的部分是在我的拍卖
模型中,我有:
The part that confuses me is that inside my Auction
model, I have:
has_many :bids, dependent: :destroy
由于我有一个从属破坏子句,为什么我仍然会收到此错误?
Since I have a dependent destroy clause, why am I still getting this error?
编辑:尝试删除整个数据库,然后重新创建/重新迁移所有内容-仍然遇到相同的错误。
I've tried dropping the whole DB, then recreating/re-migrating everything - still get the same error.
推荐答案
我的问题是我尝试删除记录时使用的是 @ auction.delete
(在我发布的屏幕快照中可见)。
My issue was that i am using @auction.delete
(visible in the screenshot I posted) when trying to remove a record.
删除将忽略我已有的任何回调。因此,即使我有一个从属的destroy子句,也不会被调用-因此Rails会引发错误。如果/当我将代码更改为 @ auction.destroy
时,调用被调用并解决了问题。
Delete will ignore any callbacks I have in place. So even though I have a dependent destroy clause, it is not being called - hence Rails is throwing an error. If/When I changed the code to read @auction.destroy
, the call-back got invoked and it solved the problem.
参考:
销毁和删除之间的区别
这篇关于错误:删除表违反外键约束。仍然从表中引用键ID(许多)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!