【发布时间】:2012-03-20 13:45:22
【问题描述】:
我有以下关联:
class Parent < ActiveRecord::Base
has_many :children, :dependent => :destroy
before_destroy :do_some_stuff
end
class Child < ActiveRecord::Base
belongs_to :parent
before_destroy :do_other_stuff
end
我想在 do_other_stuff 中知道销毁是否已被依赖 => destroy 触发,因为其中一部分将/将在 do_some_stuff 中完成
我尝试了parent.destroyed?、parent.marked_for_destruction?、parent.frozen?,但没有任何效果:/
有什么想法吗?
【问题讨论】:
-
我不认为
parent在依赖对象被销毁时会存在。它已经消失了。 -
子级在父级被销毁之前被销毁。父级上没有可用的标志,afaik。
-
@tadman 不正确。
parent在依赖对象被销毁时存在,因为子对象在parent被销毁之前被销毁。顺序似乎如下:before_destroy回调在children被销毁之前触发,children然后被销毁,before_destroy回调在parent触发,parent然后最后被销毁。你能把你想要做的事情的逻辑移到do_some_stuff方法中吗? -
感谢 cmets。实际上,顺序是
parent.some_stuff然后child.do_other_stuff然后销毁child然后销毁parent。在 do_other_stuff 上执行逻辑的事情真的很重要,我不知道如何在其他地方执行destroy仅被孩子调用:/。你不觉得如果我把像being_destroyed?这样的属性放在 parent 中可能是一个明智的想法吗?
标签: ruby-on-rails activerecord associations destroy