在rails中,如何确定记录是否被依赖的:: destroy回调破坏?

我在我的Rails应用程序中有一个记录,其中包含一个after_destroy挂钩,需要知道记录被销毁的原因。 更具体地说,如果记录在级联中被破坏,因为它的父级表示dependent: :destroy ,它需要做的事情与记录被单独销毁时不同。

我试图做的是看它的父母是否被destroyed? ,只是为了弄清楚dependent: :destroy回调是在父被销毁之前完成的。 这是有道理的,因为它应该能够失败。 (即限制)。

那么,我该怎么做?

解决方案#1

如果您的模型足够简单并且您不需要在子关系中调用任何回调,则可以在父级中使用dependent: delete_all

解决方案#2

对于更复杂的场景,您可以使用destroyed_by_association ,它在级联时返回ActiveRecord::Reflection::HasManyReflection对象,否则返回nil:

 after_destroy :your_callback def your_callback if destroyed_by_association # this is part of a cascade else # isolated deletion end end 

我刚刚在Rails 4.2中尝试了这个并且它可以工作。

资料来源: https : //github.com/rails/rails/issues/12828#issuecomment-28142658

一种方法是使用父对象中的before_destroy回调将所有子对象标记为通过父destroy销毁。 喜欢他的:

 class YourClass before_destroy :mark_children ... ... def mark_children [:association1, :association2].each do |association| # Array should inclue association names that hate :dependent => :destroy option self.send(association).each do |child| # mark child object as deleted by parent end end end end 

您还可以使用ActiveRecord Reflection自动确定哪些关联标记为:dependent => :destroy 。 在许多类中需要此function时,这样做很有帮助。