21

条件に基づいてオブジェクトのすべての依存を破棄するための最良の/DRY 方法は何でしょうか。?

元:

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 を使用する方法はありますか。依存関係を個別に破棄する方法を見つけましたが、これは DRY ではなく、さらなる関連付けに柔軟に対応できます。

注:私は例を作り上げました..実際のロジックではありません

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 に答える