如何级联删除活动记录中的多态关联



让我们以这个案例为例:

class Child < ActiveRecord::Base
    belongs_to :fruitful, polymorphic: true
end
class Parent < ActiveRecord::Base
    has_many :children, as: :fruitful, dependent: :destroy
end
# Once I create the parent and children
p = Parent.create
p.children << Child.new
p.children << Child.new
p.save
# But deleting parent does not delete children:
p.destroy  # why not?

问题变成了,活动记录的多态关联不支持"dependent::destroy"吗?我需要实现before_destroy回调来防止孤立记录吗?

应该是belongs_to :parent吗?

您可能只需要在调用parent.destroy之前先调用parent.reload,以便它知道它是children的id。执行<< Child.new时,内存中的对象可能无法准确反映数据。

编辑:这家伙解释得更好!

在实践中,我预计您通常不会在操作对象的子对象后直接销毁该对象,因此这可能是控制台问题,您不应该在应用程序中使用reload

如果您需要删除子项,并且父项也将自动删除

使用以下

class Child < ActiveRecord::Base
belongs_to :fruitful, polymorphic: true , dependent: :destroy

使用destroy而不是删除

:destroy,当对象被销毁时,将对其调用destroy关联对象。:删除,当对象被销毁时关联的对象将直接从数据库中删除调用他们的destroy方法。

最新更新