Rails - PG foreign key violation on DELETE

I have an application with Venuesand Clients.

Each institution has many clients:

class Venue < ActiveRecord::Base
  has_many :clients
end

When I try to delete a place, Postgres complains about violation of foreign key restrictions:

PG::ForeignKeyViolation: ERROR: update or delete on table "venues" violates foreign key constraint "fk_rails_3afaf2f5fc" on table "clients" DETAIL: Key (id)=(3) is still referenced from table "clients". : DELETE FROM "venues" WHERE "venues"."id" = $1

It would be easy to solve by adding dependent: :destroyto the association.

But I want to keep customers, even if they no longer have a place.

+4
source share
1 answer

You can use nullify. It will set venue_idthe client to null. But you need to remove the foreign key constraint from the column.

has_many :clients, dependent: :nullify
+8
source

All Articles