ruby-on-rails - 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
解决方案
您可以使用子属性中的属性来查看对象是否作为其父destroyed_by_association
对象的一部分被销毁。dependent: :destroy
推荐阅读
- javascript - reactjs中如何将字符串转换为数组?
- node.js - Async Await mongoDb 总是返回 undefined
- python - TypeError: __init__() 接受 1 个位置参数,但给定了 2 个 Python
- javascript - 无法调用更高级别的函数
- linux - Geany - 如何轻松配置 ARM C/C++ 工具链以进行交叉编译
- exception - IIS下如何将dotnet core webapp切换到开发模式
- laravel - 使用 Laravel @push Blade 模板引擎动态推送脚本
- dotnetnuke - 如何从外部非 DNN 网站访问 2sxc API
- reactjs - 如何在 Gatsby 中使用 Fabric?
- matlab - 如何在Matlab中对具有给定容差的点进行分组