Home > Back-end >  How to add `:dependent => :destroy` declaration on already created Rails ActiveRecord Postgresql
How to add `:dependent => :destroy` declaration on already created Rails ActiveRecord Postgresql

Time:12-16

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related