Reputation: 2929
I'm getting the following error:
PG::ForeignKeyViolation: ERROR: update or delete on table "sites" violates foreign key constraint "fk_rails_b1cb5ea385" on table "domains" DETAIL: Key (id)=(1) is still referenced from table "domains". : DELETE FROM "sites" WHERE "sites"."id" = $1
This is because there is a Domain record that has a reference to the site being deleted, I know this because manually removing the site_id
causes the error to go away (of course this is not the way to do this, this was done for checking purposes only).
However as can be seen in the model:
class Site < ApplicationRecord
enum environment: %i{development staging production}
belongs_to :project
belongs_to :client
has_one :domain, dependent: :nullify
has_many :servers, through: :domain
end
I am indeed asking active record to nullify the domain ( though I am considering outright destroying it, that isn't relevant to this issue).
This association is also used in Server
:
class Server < ApplicationRecord
before_save :set_domains, if: :sites_id_changed?
has_many :domains, dependent: :nullify
has_many :sites, through: :domains
def clients
self.sites.map(&:client).flatten
end
def set_domains
domains = get_domains Site.where(id: self.site_ids).all
domains += get_domains domains,:domains
self.domains = domainsprimary_domains
end
private
def get_domains(object,meth=:domain)
objects.first.blank? ? [] : objects.map(&meth).flatten
end
end
and Domain
:
class Domain < ApplicationRecord
alias_attribute :aliases, :domains
alias_attribute :alias_of, :domain
has_many :domains, dependent: :nullify
belongs_to :domain, optional: true
belongs_to :site, optional: true
belongs_to :server, optional: true
def alias?
!self.alias_of.blank?
end
accepts_nested_attributes_for :domains, allow_destroy: true
end
Why despite being asked to so do is active record not nullifying the reference to site table in the domain table despite being asked (seemingly at least) to do so?
Upvotes: 1
Views: 1295
Reputation: 1038
I have run into something similar in the past. You are correct that this is a situation where you are running into a database-level foreign key constraint.
If you're using PG, for example, here are some helpful docs with more information on the constraint in general.
As far as solving your actual issue, the SO response that helped me overcome this error and get things working again I found here.
Let me know if that works/helps! :)
Upvotes: 3