0

我有三个相关的模型。如此定义的公寓、订阅和发票

class Apartment < ApplicationRecord
 has_one :subscription, dependent: :destroy
end
class Subscription < ApplicationRecord
 belongs_to :apartment
 has_one :invoice, dependent: :destroy
end
class Invoice < ApplicationRecord
 belongs_to :subscription, optional: true
end

删除公寓时出现以下错误

Invoice Destroy (0.5ms)  DELETE FROM "invoices" WHERE "invoices"."id" = $1  [["id", 30]]
  Subscription Destroy (0.7ms)  DELETE FROM "subscriptions" WHERE "subscriptions"."id" = $1  [["id", 25]]
  Apartment Destroy (1.1ms)  DELETE FROM "apartments" WHERE "apartments"."id" = $1  [["id", 23]]
   (0.2ms)  ROLLBACK TO SAVEPOINT active_record_1
Traceback (most recent call last):
        1: from (irb):1
ActiveRecord::InvalidForeignKey (PG::ForeignKeyViolation: ERROR:  update or delete on table "apartments" violates foreign key constraint "fk_rails_1c3da2c0e9" on table "subscriptions")
DETAIL:  Key (id)=(23) is still referenced from table "subscriptions".

这意味着在对 Apartment 对象调用 destroy 方法时,相关订阅记录不会被删除。我会期待这条线

 has_one :subscription, dependent: :destroy

来解决这个问题。您对如何解决此问题有一些想法吗?谢谢!

4

0 回答 0