删除表违反外键约束

删除表违反外键约束

本文介绍了错误:删除表违反外键约束。仍然从表中引用键ID(许多)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与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 Bids. However when I try and delete an auction (that has bids present) I get the following error:

删除没有出价没有错误。

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(许多)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 01:29