我正在使用 Rails 和 PostgreSQL,并且有一个基本的一对多关系,一个 Auction
有很多 Bid
。但是,当我尝试删除拍卖(存在出价)时,出现以下错误:
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".
删除没有出价的拍卖不会出错。
让我感到困惑的是,在我的Auction
模型中,我有:
has_many :bids, dependent: :destroy
既然我有一个 dependent destroy 子句,为什么我仍然会收到这个错误?
编辑:我试过删除整个数据库,然后重新创建/重新迁移所有内容 - 仍然遇到相同的错误。
最佳答案
从 Rails v4.2 你可以这样做:
创建迁移以更新外键
20160321165946_update_foreign_key.rb
class UpdateForeignKey < ActiveRecord::Migration
def change
# remove the old foreign_key
remove_foreign_key :posts, :users
# add the new foreign_key
add_foreign_key :posts, :users, on_delete: :cascade
end
end
关于ruby-on-rails - ERROR : delete on table violates foreign key constraint. key id 仍然从表中引用(很多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28996773/