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

时间:2014-02-05 13:32:44

标签: ruby-on-rails activerecord callback

我的Rails应用程序中有一条带有after_destroy挂钩的记录,需要知道记录被销毁的原因。更具体地说,如果记录在级联中被销毁,因为它的父级称为dependent: :destroy,则它需要采取与记录单独销毁时不同的方式。

我尝试做的是查看其父级是否为destroyed?,只是为了确定在父级被销毁之前完成了dependent: :destroy次回调。这是有道理的,因为它应该能够失败。 (即限制)。

那么,我该怎么做?

2 个答案:

答案 0 :(得分:8)

解决方案#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

答案 1 :(得分:3)

执行此操作的一种方法是使用父对象中的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 Reflections自动确定哪些关联标记为:dependent => :destroy。在许多类中需要此功能时,这样做很有帮助。