【问题标题】:Is there a way to know if a "destroy" called to a model comes from a "dependent" relation in Rails?有没有办法知道调用模型的“破坏”是否来自 Rails 中的“依赖”关系?
【发布时间】:2019-09-08 01:37:05
【问题描述】:

给定一个具有多种颜色的产品模型

class Product < ApplicationRecord
    has_many :colors, dependent: :destroy
end

还有一个属于 Product 的颜色模型,带有一个 after_destroy,如果产品没有更多颜色,则将其销毁。

class Color < ApplicationRecord
  belongs_to :product

  after_destroy do |color|
    product = color.product
    product.destroy! if product.colors.count.zero?
  end
end

当我销毁一种颜色,甚至所有颜色时,一切正常。 但是当我尝试销毁产品时,它会引发:ActiveRecord::RecordNotDestroyed (Failed to destroy the record)

在这一行,内部颜色模型:product.destroy! if product.colors.count.zero?

经过一番测试,我认为这与它在产品和颜色之间创建的循环破坏有关。有没有办法发现 Color 对象是否被“has_many”依赖破坏了?

【问题讨论】:

  • 你可以试试看product.marked_for_destruction?

标签: ruby-on-rails destroy


【解决方案1】:

为关联定义了 4 个回调(before_add、after_add、before_remove 和 after_remove)。你可能想要 after_remove:

class Product < ApplicationRecord
  has_many :colors, dependent: :destroy, after_remove: :cleanup_product

  def cleanup_product(color)
    color.product.destroy if color.product.colors.empty?
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-05
    • 2014-03-11
    • 2015-11-01
    • 1970-01-01
    • 2018-02-21
    • 2021-06-07
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多