skip to Main Content

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


  1. Chosen as BEST ANSWER

    I fixed my problem like so:

    class UpdateChartForeignKey < ActiveRecord::Migration[7.0]
      def change
        remove_foreign_key :comments, :posts
        add_foreign_key :comments, :posts, on_delete: :cascade
      end
    end
    

  2. class User < ApplicationRecord
       has_many :posts, dependent: :destroy
    end
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search