尽管被要求这样做,但Activerecord的关系并没有取消依赖



我会收到以下错误:

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

这是因为有一个域记录,该记录引用了被删除的站点,我知道这是因为手动删除site_id会导致错误消失(当然,这不是这样做的方法,这是完成的,这是完成的仅用于检查目的)。

但是,在模型中可以看出:

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

我确实在要求积极记录以使域无效(尽管我正在考虑彻底销毁它,这与此问题无关)。

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

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

为什么被要求这样做,尽管有主动记录,但尽管被要求(至少似乎似乎)这样做?

我过去遇到了类似的东西。您是正确的,这是您遇到数据库级外键约束的情况。

例如,如果您使用的是PG,这里有一些有用的文档,其中包含有关约束的更多信息。

就解决您的实际问题而言,SO响应帮助我克服了此错误并使事情再次工作我在这里找到。

让我知道这是否有效/有帮助!:)

最新更新