21

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

前任:

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

条件将是 销毁:

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

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

注意:我已经编造了这个例子..不是一个实际的逻辑

4

1 回答 1

40

不,您应该删除: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 
于 2011-05-18T19:50:04.183 回答