基于条件销毁对象的所有从属对象的最佳/干式方法是什么??
例如:
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?我已经找到了单独销毁被依赖对象的方法,但这对于进一步的关联来说并不是干练和灵活的,
注意:这个例子是我编的。不是一个实际的逻辑
发布于 2011-05-19 03:50:04
不是的。您应该删除: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
https://stackoverflow.com/questions/6049806
复制相似问题