I have a post
ActiveRecord model that has_many
comments, but I forgot to add :dependent => :destroy
upon declaring it. Now I have several posts with comments and I cannot delete them as I get this error:
PG::ForeignKeyViolation: ERROR: update or delete on table "posts" violates foreign key constraint "fk_rails_c9b8ba77e9" on table "comments"
DETAIL: Key (id)=(2) is still referenced from table "comments".
I after the fact added the :dependent => :destroy
declaration, but I am pretty sure I cannot do that, so how do I create a migration that does it?
2
Answers
I fixed my problem like so:
This will add the :dependent => :destroy declaration to the User model’s association with the posts table, indicating that when a user is deleted, all of the associated posts should also be deleted.