Rails - AciveRecord use :dependent => :destroy on condition
Asked Answered
D

1

21

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

Ex:

class Worker < ActiveRecord::Base
 has_many :jobs , :dependent => :destroy
 has_many :coworkers , :dependent => :destroy
 has_many :company_credit_cards, :dependent => :destroy
end 

condition will be on Destroy:

if self.is_fired? 
 #Destroy dependants records
else
 # Do not Destroy records
end 

Is There a Way to use Proc in the :dependent condition. I have found the methods to destroy the dependents individually, but this is not DRY and flexible for further associations,

Note: I have made up the example.. not an actual logic

Decasyllable answered 18/5, 2011 at 19:8 Comment(0)
H
41

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 
Hail answered 18/5, 2011 at 19:50 Comment(2)
Just be careful with callbacks as those works fine unless you are processing sone huge data where those callbacks would make a great performance issue for you. A solution could be 'mass delete` which not supported in rails for associations so you would need to write some codeClare
What does the .is_fired? method do? I cannot seem to find it anywhere else.Anamorphic

© 2022 - 2024 — McMap. All rights reserved.