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!
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With