Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - PG Foreign Key Violation on DELETE

I have an application that has Venues and Clients.

Each venue has many clients:

class Venue < ActiveRecord::Base
  has_many :clients
end

When I try to delete some venue, Postgres complains about foreign key constraint violation:

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 simple to solve by adding dependent: :destroy to the association.

But I want to keep the clients, even if they have no more venue.

like image 213
gcstr Avatar asked Dec 15 '22 07:12

gcstr


1 Answers

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

has_many :clients, dependent: :nullify
like image 182
beydogan Avatar answered Dec 30 '22 02:12

beydogan