导轨 - AciveRecord使用方法:依赖=> :销毁条件 [英] Rails - AciveRecord use :dependent => :destroy on condition

查看:109
本文介绍了导轨 - AciveRecord使用方法:依赖=> :销毁条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么将是最好的/干法破坏基于一个条件对象的所有家属。 ?

例如:

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 

这篇关于导轨 - AciveRecord使用方法:依赖=&GT; :销毁条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆