首页 > 解决方案 > Rails - 检查父对象是否被销毁并在依赖项上调用销毁

问题描述

我有以下内容:

class ModelA < ApplicationRecord
  has_many :model_bs, dependent: :destroy
end

class ModelB < ApplicationRecord
  belongs_to :model_a
  after_destroy :action_only_if_model_a_exists

  private

  def action_only_if_model_a_exists
    # Do things
  end
end

当我调用时model_a.destroy,我需要能够在 ModelB 的action_only_if_model_a_exists回调中确定关联的 ModelA 是否仍然存在或即将被销毁。

是否有一个很好的内置 Rails 方法可以做到这一点,或者我是否需要在较早的回调(例如before_destroy)中在 ModelA 中设置标志的路径,然后我可以检查 ModelB 的回调?

编辑

我已经进行了多次测试并确认在action_only_if_model_a_exists回调中,执行以下操作无济于事:

> model_a.persisted?
true

> model_a.destroyed?
false

> model_a.frozen?
false

标签: ruby-on-railsactivemodel

解决方案


您可以使用子属性中的属性来查看对象是否作为其父destroyed_by_association对象的一部分被销毁。dependent: :destroy


推荐阅读