gcstr
gcstr

Reputation: 1537

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.

Upvotes: 4

Views: 5663

Answers (1)

beydogan
beydogan

Reputation: 1110

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

Upvotes: 12

Related Questions