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

前端 未结 5 1566
伪装坚强ぢ
伪装坚强ぢ 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:33

    carp's answer above will work if you set prepend to true on the before_destroy method. Try this:

    Child:

    belongs_to :parent
    before_destroy :prevent_destroy
    attr_accessor :destroyed_by_parent
    
    ...
    
    private
    
    def prevent_destroy
      if !destroyed_by_parent
        self.errors[:base] << "You may not delete this child."
        return false
      end
    end
    

    Parent:

    has_many :children, :dependent => :destroy
    before_destroy :set_destroyed_by_parent, prepend: true
    
    ...
    
    private
    
    def set_destroyed_by_parent
      children.each{ |child| child.destroyed_by_parent = true }
    end
    

    We had to do this because we're using Paranoia, and dependent: delete_all would hard-delete rather than soft-delete them. My gut tells me there's a better way to do this, but it's not obvious, and this gets the job done.

提交回复
热议问题