由网友(祢曾明媚了那段斑驳时光╮)分享简介:什么将是最好的/干法破坏基于一个条件对象的所有家属。 ? 例如:class Worker :destroyhas_many :coworkers , :dependent => :destroyhas_many...
什么将是最好的/干法破坏基于一个条件对象的所有家属。 ?
例如:
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在:相关情况。 我发现摧毁个别家属的方法,但这是不干燥和灵活的进一步协会,
Is There a Way to use Proc in the :dependent condition. I have found the methods to destroy the dependents individually, but this is not DRY and flexible for further associations,
注:我已经决定了的例子..而不是实际的逻辑
Note: I have made up the example.. not an actual logic
推荐答案
没有。您应该删除:依赖=&GT; :摧毁
并添加 after_destroy
回调,你可以写任何你想要的逻辑
No. You should remove :dependent => :destroy
and add after_destroy
callback where you can write any logic you want.
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
相关推荐
最新文章