Rails - AciveRecord 使用:dependent => :有条件销毁
根据条件销毁对象的所有依赖项的最佳/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。 我已经找到了单独销毁依赖项的方法,但这对于进一步的关联来说并不干燥和灵活,
注意:我已经编写了示例..不是实际的逻辑
What will be the best/DRY way to destroy all the dependents of an object based on a condition. ?
Ex:
class Worker < ActiveRecord::Base
has_many :jobs , :dependent => :destroy
has_many :coworkers , :dependent => :destroy
has_many :company_credit_cards, :dependent => :destroy
end
condition will be
on Destroy:
if self.is_fired?
#Destroy dependants records
else
# Do not Destroy records
end
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您应该删除
:dependent => :destroy
并添加after_destroy
回调,您可以在其中编写您想要的任何逻辑。No. You should remove
:dependent => :destroy
and addafter_destroy
callback where you can write any logic you want.