Rails - AciveRecord use :dependent => :destroy on condition

后端 未结 1 1720

What will be the best/DRY way to destroy all the dependents of an object based on a condition. ?

Ex:

class Worker < ActiveRecord:         


        
1条回答
  •  独厮守ぢ
    2021-01-01 14:59

    No. You should remove :dependent => :destroy and add after_destroy callback where you can write any logic you want.

    class Worker < ActiveRecord::Base
      has_many :jobs
      has_many :coworkers
      has_many :company_credit_cards
      after_destroy :cleanup
    
      private
      def cleanup
        if self.is_fired?
          self.jobs.destroy_all
          self.coworkers.destroy_all
          self.company_credit_cards.destroy_all
        end
      end
    end 
    

    0 讨论(0)
提交回复
热议问题