Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 784
VelLes Avatar asked May 18 '11 19:05

VelLes


People also ask

What is the difference between dependent => destroy and dependent => Delete_all in Rails?

What is the difference between :dependent => :destroy and :dependent => :delete_all in Rails? There is no difference between the two; :dependent => :destroy and :dependent => :delete_all are semantically equivalent.

Why use dependent destroy in Rails?

dependent: :destroy Rails, when attempting to destroy an instance of the Parent, will also iteratively go through each child of the parent calling destroy on the child. The benefit of this is that any callbacks and validation on those children are given their day in the sun.

What does dependent destroy do?

:destroy causes all the associated objects to also be destroyed.

What is the difference between delete and destroy in Rails?

Rails Delete operation using delete method Unlike the destroy method, with delete, you can remove a record directly from the database. Any dependencies to other records in the model are not taken into account. The method delete only deletes that one row in the database and nothing else.


1 Answers

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 
like image 64
fl00r Avatar answered Oct 12 '22 00:10

fl00r