Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR: delete on table violates foreign key constraint. Key id is still referenced from table (many)

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:

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 

Error Screen Shot (better_error gem)

Since I have a dependent destroy clause, why am I still getting this error?

EDIT: I've tried dropping the whole DB, then recreating/re-migrating everything - still get the same error.

like image 946
TABISH KHAN Avatar asked Mar 11 '15 20:03

TABISH KHAN


People also ask

How to remove foreign key reference in MySQL?

Dropping Foreign Key Constraints You can drop a foreign key constraint using the following ALTER TABLE syntax: ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause defined a CONSTRAINT name when you created the constraint, you can refer to that name to drop the foreign key constraint.

How to update foreign key constraint in MySQL?

Here is how you would do that: ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE SET NULL; And that's it!! That's how you change a foreign key constraint in MySQL!

How to use on delete SET NULL in MySQL?

SET NULL : Delete or update the row from the parent table and set the foreign key column or columns in the child table to NULL . Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported. If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL .


2 Answers

From Rails v4.2 you can do this:

Create a migration to update the foreign keys

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 
like image 124
Mohamed Ziata Avatar answered Sep 23 '22 16:09

Mohamed Ziata


Are you using delete or destroy to remove the objects? I think you are using delete and you want to use destroy

See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Delete+or+destroy-3F

like image 44
John Naegle Avatar answered Sep 19 '22 16:09

John Naegle