【问题标题】:Rails :dependent => destroy with conditionsRails :dependent => 有条件的销毁
【发布时间】:2013-03-27 09:01:31
【问题描述】:

假设我有狗、皮带和主人……如果我破坏皮带,我也想破坏狗……但如果狗有主人,则不会……

【问题讨论】:

  • 您可以为此使用回调 after_destroy。有关详细信息,请参阅 [this answer][1]。 [1]:stackoverflow.com/questions/6049806/…
  • 你能在 after_destroy 之后调用 'self' 吗?
  • 我自己没有尝试过,但我认为你可以。即使在销毁之后,模型对象也应该仍然存在。
  • 太酷了。我没有意识到这一点。

标签: ruby-on-rails


【解决方案1】:

您不想在这里使用:dependent => :destroy,而是像这样使用before_destroy 回调:

#leash.rb

before_destroy :destroy_dog

def destroy_dog
  dog.destroy unless dog.owner
end

【讨论】:

  • 我在想像 self.dog.destroy 之类的东西,除非 self.dog.owner
  • ...但不确定是否可以在 after_destroy 之后调用 self
  • 是的,before_destroy 在这里可能更合适。相应地更新了答案。
  • 嘿,我想你需要把 self.dog.destory 除非 self.dog.owner 没有?
  • self 在这里是不必要的,它是隐含的。它起作用的原因是因为 ruby​​ 试图找到一个局部变量(即dog),如果没有找到,它会将它发送到self。试试看:)
【解决方案2】:
class Book < ApplicationRecord
  belongs_to :author, -> { where active: true },
                        dependent: :destroy
end

也适用于has_many,它根据where 条件销毁对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多