Rails: how to disable before_destroy callback when it's being destroyed because of the parent is being destroyed (:dependent => :destroy)

前端 未结 5 1562
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 06:06

I have two classes: Parent and Child with

Child:

belongs_to :parent

and

Parent

has_many :children, :dependent          


        
5条回答
  •  鱼传尺愫
    2021-02-05 06:49

    There's probably a way to accomplish this in a less hacky fashion, but here's an (untested!) idea: add an attr_accessor :destroyed_by_parent to Child and edit Child's before_destroy filter to allow the destroy when it's true.

    Add a before_destroy filter to Parent that iterates over all its children:

    private
    
    # custom before_destroy
    def set_destroyed_by_parent
      self.children.each {|child| child.destroyed_by_parent = true }
    end
    

    Provided that the destroy triggered by :dependent => :destroy is executed on the instanced children of the Parent object, it could work. If it instantiates the children separately, it won't work.

提交回复
热议问题