5

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!

peterh
  • 11,875
  • 18
  • 85
  • 108

3 Answers3

7

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
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

Update the below line in your Post model as below

has_many :comments, dependent: :destroy 

You have to mention dependent: :destroy in your Post model. So when any post get to deleted by post.destroy, It deletes the all dependent records of Comment model.

Hope this will resolve your issue

hgsongra
  • 1,454
  • 15
  • 25
1

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

Aschen
  • 1,691
  • 11
  • 15