ruby-on-rails – Rails – AciveRecord使用:dependent =>:
发布时间:2020-12-16 20:30:23 所属栏目:百科 来源:网络整理
导读:什么是最好的/ DRY的方式来销毁一个对象的所有依赖的基于条件的依赖. ? 例如: class Worker ActiveRecord::Base has_many :jobs,:dependent = :destroy has_many :coworkers,:dependent = :destroy has_many :company_credit_cards,:dependent = :destroye
什么是最好的/ 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |