2009-04-19 71 views

回答

12

我已经找到了解决方案似乎是一个after_destroy回调,比如这个:

class Parent < ActiveRecord::Base 
    has_many :children, :through => :parentage 
    after_destroy :destroy_orphaned_children 

    private 

    def destroy_orphaned_children 
    children.each do |child| 
     child.destroy if child.parents.empty? 
    end 
    end 

end 
+0

捅了一个老问题/答案,我有一个`的has_many:through` ASSOCATION;我在直通模型上调用了'destroy',但我想删除可能成为孤儿的协会另一端的任何模型。我把这段代码放在我的遍历模型中,并且由于最后被销毁的模型只是一个`belongs_to`,所以我去掉了每个包装的调用。感谢您推向正确的方向。 – 2012-03-29 19:41:49

3

在加盟模式,用 “belongs_to的:模型,依赖:消灭”

例如,如果要摧毁病人一旦他们的医生被破坏,医生的has_many患者虽然约会

Class Appointment 
    belongs_to :doctor 
    belongs_to :patient, dependent: :destroy 

Class Doctor 
    has_many :appointments, dependent: :destroy 
    has_many :patients, through: :appointments 

Class Patient 
    has_many :appointments 
    has_many :doctors, through: :appointments 
+2

我喜欢摧毁所有患者的想法:)) – 2013-06-06 12:34:45

相关问题