Ruby on rails 如何知道模型何时被a:dependent=>;自动卸载:破坏铁路?

Ruby on rails 如何知道模型何时被a:dependent=>;自动卸载:破坏铁路?,ruby-on-rails,activerecord,associations,destroy,Ruby On Rails,Activerecord,Associations,Destroy,我有以下协会: 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 类父级:销毁 在毁灭之前:做一些东西 结束 类Ch

我有以下协会:

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
类父级:销毁
在毁灭之前:做一些东西
结束
类Child
我想知道在do_other_stuff中销毁是否由dependent=>destroy触发,因为部分销毁将在do_other_stuff中完成

我尝试了
parent.destroming?
parent.marked\u for\u destroming?
parent.freezed?
,但没有任何效果:/


有什么想法吗?

可能是这样的:

class Parent < ActiveRecord::Base
    has_many :children
    before_destroy :some_stuff
    def some_stuff
        children.each do |child|
            child.parent_say_bye
        end
    end
end

class Child < ActiveRecord::Base
    belongs_to :parent
    before_destroy :do_other_stuff
    def parent_say_bye
        #do some stuff
        delete
    end
end
类父级
您可以使用关联回调(
在删除之前
在删除之后

类父级:destroy,:before\u remove=>:do\u foo
在销毁之前:做吧
def do_酒吧
结束
迪夫多福
结束
结束

我认为当相关对象被销毁时,
父对象
不会存在。它已经不见了。孩子们在父母被毁灭之前就被毁灭了。父级上没有可用的标志,afaik。@tadman不正确<代码>父对象
在销毁从属对象时存在,因为子对象在销毁父对象之前被销毁。顺序似乎如下:
在销毁之前
子对象
启动回调,在子对象被销毁之前,
子对象
然后被销毁,
在销毁之前
对父对象启动回调,
父对象
最后被销毁。你能把你想做的事情的逻辑转移到
做一些事情
方法中吗?谢谢你的评论。实际上,顺序是
父级。一些东西
然后
子级。做其他东西
然后销毁
子级
然后销毁
父级
。在do_other_stuff上执行逻辑是非常关键的,我不知道在其他地方如何执行,因为
destroy
仅为子对象调用:/。你不认为如果我在parent中添加一个像
被销毁?
这样的属性可能是一个明智的主意吗?是的,即使没有必要使用
:dependent=>:destroy
,这也可以做到。如果这样做,我会有点沮丧,因为我会重做rails建议的东西……我认为这不是一个好的解决方案,但它是有效的。不过,谢谢你提到的
:dependent=>:destroy
,这就是为什么我最终得到了
:dependent=>:delete_all
,并在parentHi的
destroy
之前在
中完成这项工作(记录销毁),很好的捕获。最后我得到了
:dependent=>:delete_all
并在父级的
销毁之前完成了工作(记录销毁)。
class Parent < ActiveRecord::Base
  has_many :children, :dependent => :destroy, :before_remove => :do_foo

  before_destroy :do_bar

  def do_bar
  end

  def do_foo
  end
end