Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update or delete on table "x" violates foreign key constraint "fk_rails_5a7b40847a" on table "x" [duplicate]

I am building a rails app (5.1.1) that has the equivalent of posts and comments linked to them.

Everything seems to be working just fine but when I try to delete a post that has comments I get this error:

PG::ForeignKeyViolation: ERROR:  update or delete on table "posts" violates foreign key constraint "fk_rails_5a7b40847a" on table "comments"
DETAIL:  Key (id)=(3) is still referenced from table "comments".
: DELETE FROM "posts" WHERE "prototypes"."id" = $1"

The error seems pretty straight forward but I'm really new to rails and postgresql so I'm looking for some help on that!

like image 537
Thomas Cailhol Avatar asked Mar 08 '23 19:03

Thomas Cailhol


2 Answers

It depends what you want to do with the post's comments on its deletion. In case you want to delete them on cascade, for example:

post.rb

has_many :comments, dependent: :destroy
like image 172
Ursus Avatar answered May 03 '23 15:05

Ursus


It's because you have a constraint in your database.
I presume that the foreign key post_id in table comments must exist in the associated table posts.
That is certainly because you specify the foreign key relation in the migration with rails g model Comment post:references.

You have to specify what to do with associated models on deletion :

class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy # destroy associated comments
end

Then call method post.destroy instead of post.delete on your record

See has_many for other options

like image 21
Aschen Avatar answered May 03 '23 15:05

Aschen