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

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

    In Rails 4 you can do the following:

    class Parent < AR::Base
      has_many :children, dependent: :destroy
    end
    
    class Child < AR::Base
      belongs_to :parent
    
      before_destroy :check_destroy_allowed, unless: :destroyed_by_association
    
      private
    
      def check_destroy_allowed
        # some condition that returns true or false
      end
    end
    

    This way, when calling destroy directly on a child, the check_destroy_allowed callback will be run, but when you call destroy on the parent, it won't.

提交回复
热议问题