什么是最好的/ 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
有没有办法在依赖条件下使用Proc.
我已经找到了分别摧毁家属的方法,但是对于进一步的协会来说,这并不是干脆和灵活的,
注意:我已经做了例子..不是一个实际的逻辑
解决方法
不,你应该删除:dependent => :摧毁并添加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