【问题标题】:How to know when the model is destoyed automatically by a :dependent => :destroy in rails?如何知道模型何时被 :dependent => :destroy in rails 自动销毁?
【发布时间】: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


【解决方案1】:

您可以使用关联回调(before_removeafter_remove

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

【讨论】:

  • 嗨,不错的收获。我最终得到了:dependent =&gt; :delete_all,并在父级的before_destroy 中完成了这项工作(记录破坏)。
【解决方案2】:

也许是这样的:

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

【讨论】:

  • 是的,即使 :dependent =&gt; :destroy 没有必要,这也可以解决问题。这样做我会有点沮丧,因为我有点重做 Rails 提出的一些事情......
  • 我认为这不是一个好的解决方案,但它确实有效。不过感谢您提及:dependent =&gt; :destroy
  • 这就是为什么我最终选择了:dependent =&gt; :delete_all 并在父级的before_destroy 中完成工作(记录破坏)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 2023-03-14
相关资源
最近更新 更多