2009-04-19 73 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

相關問題