出于某種原因,我PG::ForeignKeyViolation: ERROR在銷毀記錄后得到了回報。
在這里我有遷移
create_table :vacation_transactions do |t|
t.belongs_to :vacacion, index: true, foreign_key: true, null: true
t.references :vacacion_percibida, index: true, foreign_key: true, null: true
t.timestamps
end
我這里有模型
class Vacacion < ApplicationRecord
has_many :vacation_transactions, dependent: :destroy
end
class VacacionPercibida < ApplicationRecord
has_many :vacation_transactions, dependent: :nullify
end
class VacationTransaction < ApplicationRecord
belongs_to :vacacion, optional: true
belongs_to :vacacion_percibida, optional: true
end
這里我有一個例子:帶有 id=348 的 vacacion,帶有 id=950 的 vacacion_percibida 和帶有
#<VacationTransaction:0x00007f390901cc48> {
:id => 20,
:vacacion_id => 348,
:vacacion_percibida_id => 950,
:created_at => some_date,
:updated_at => some_date
}
但是當我試圖用 id=348 摧毀 vacacion 時,噩夢就發生了
Vacacion.find(348).destroy!
# PG::ForeignKeyViolation: ERROR: update or delete on table "vacacions" violates foreign key constraint "fk_rails_ae595e109b"
# on table "vacation_transactions" DETAIL: Key (id)=(348) is still referenced from table "vacation_transactions"
# if I do the next lines I get the same error
VacationTransaction.find(20).destroy! # cool
VacationTransaction.find(20) # ActiveRecord::RecordNotFound, that means the record is destroyed
Vacacion.find(348).destroy! # Same PG::ForeignKeyViolation: ERROR
我嘗試在銷毀 id=348 的 vacacion 時除錯 ActiveRecord,我發現了這個
# lib/active_record/associations/has_many_association.rb
when :destroy
load_target.each { |t| t.destroyed_by_association = reflection }
# load_target actually has the vacation_transaction record to destroy
destroy_all
# it actually destroys the vacation_transaction, in the console I can see the DELETE FROM "vacaciones_percibidas" WHERE "vacaciones_percibidas"."id" = $1
# but the error still happens
else
delete_all
end
此外,這個問題只發生在vacacion_idFK 上,并且只發生在 Vacacion 的少量記錄中
我正在使用 ruby?? 2.7.4p191、Rails 6.0.4.1、ActiveRecord 6.0.4.1
那么,我錯過了什么?
謝謝。
uj5u.com熱心網友回復:
我認為你需要修改你的假期模型并添加 accepts_nested_attributes_for
class Vacacion < ApplicationRecord
has_many :vacation_transactions, dependent: :destroy
accepts_nested_attributes_for :vacation_transactions, allow_destroy: true
end
uj5u.com熱心網友回復:
因此,我嘗試洗掉 FK 并再次添加它,但問題仍然存在。在最后一次嘗試中,我洗掉并再次添加了 FK,但指定了級聯引數add_foreign_key :vacation_transactions, :vacacions, on_delete: :cascade,現在問題解決了。
我仍然不明白為什么我必須在這個特定的 FK 中指定這一點,以及這個解決方案是否會在未來引發其他問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/328700.html
上一篇:Rails路由可選段映射問題
下一篇:陣列內的Rails同步范圍
