update or delete on table "x" violates foreign key constraint "fk_rails_5a7b40847a" on table "x" [duplicate]
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.rbhas_many :comments, dependent: :destroy
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
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 commentsend
Then call method post.destroy
instead of post.delete
on your record
See has_many for other options