sam bukhari
sam bukhari

Reputation: 11

ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_03de2dc08c" on table "comments"

I am stuck on this error and not able to figure out whats wrong.

rails aborted! ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_03de2dc08c" on table "comments" DETAIL: Key (id)=(11) is still referenced from table "comments". : DELETE FROM "users" WHERE "users"."id" = $1 #31

Upvotes: 1

Views: 1969

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

Sounds like user number 11 made some comments and the user hence cannot be deleted because those comments still refer to that user. This is what a foreign key is- entries on the comments table (a child table) are keyed to the parent table (user) - the parent cannot be deleted because that would leave orphan records

Delete user 11's comments first, or change the foreign key so it's "on delete cascade" mode - deletion of the parent will cause automatic deletion of the child records

Upvotes: 3

Related Questions