Rails : PostgreSQL : ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation

 

when invoking commands like

User.find(3).payment_sources.default.delete

I got this error

SQL (1.3ms) DELETE FROM "payment_sources" WHERE "payment_sources"."id" = $1 [["id", 1]]
PG::ForeignKeyViolation: ERROR: update or delete on table "payment_sources" violates foreign key constraint "fk_rails_7a7XXXd48" on table "pacts"
DETAIL: Key (id)=(1) is still referenced from table "pacts".
: DELETE FROM "payment_sources" WHERE "payment_sources"."id" = $1
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "payment_sources" violates foreign key constraint "fk_rails_7a7XXXd48" on table "pacts"

 

Solution

class UpdateForeignkeyInfoInPacts < ActiveRecord::Migration
  def change
    add_foreign_key "pacts", "payment_sources", on_delete: :nullify
  end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s