Rails – AciveRecord使用:dependent =>:在条件下销毁

根据条件销毁对象的所有依赖项的最佳/干燥方法是什么。

例如:

class Worker  :destroy has_many :coworkers , :dependent => :destroy has_many :company_credit_cards, :dependent => :destroy end 

条件将在Destroy上:

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

有没有办法在依赖条件下使用Proc。 我已经找到了单独销毁家属的方法,但这对于进一步的关联来说并不是干燥和灵活的,

注意:我已经编写了示例..而不是实际的逻辑

不。你应该删除:dependent => :destroy并添加after_destroy回调,你可以在其中编写你想要的任何逻辑。

 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