2013-04-30 71 views
4

我的車型有:如何刪除嵌套的has_many關聯中關聯的所有對象?

class Campaign < ActiveRecord::Base 
    has_many :days, dependent: :destroy 
end 

class Day < ActiveRecord::Base 
    belongs_to :campaign 

    has_many :time_slots 
    before_destroy { time_slots.destroy_all } 
end 

class TimeSlot < ActiveRecord::Base 
    belongs_to :day 
    has_and_belongs_to_many :users 
end 

我希望能夠刪除廣告,並有與其關聯的所有日子裏,和時隙刪除。我還想要刪除time_slot_users連接表中的記錄。

我試過使用dependent: :destroy,但似乎沒有級聯?我應該使用before_destroy回調嗎?

destroydestroy_all有什麼區別?我已閱讀:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Delete+or+destroy%3F和區別仍然是模糊的。

回答

3

這是我如何做的:

class Campaign < ActiveRecord::Base 
    has_many :days, dependent: :destroy 
    has_many :members 
    has_many :users, :through => :members 
end 

class Day < ActiveRecord::Base 
    belongs_to :campaign 
    has_many :time_slots, dependent: :destroy 
end 

class TimeSlot < ActiveRecord::Base 
    belongs_to :day 
    has_and_belongs_to_many :users 

    before_destroy do |time_slot| 
     users.delete 
    end 
end 

對於的has_many關係,使用依賴於:破壞。這將導致在每個關聯的廣告系列,日期和時段上調用銷燬。要刪除用戶和時間段之間的關聯,time_slot_users表中的記錄添加了before_destroy回調。我使用delete,因爲可以在不創建對象實例的情況下移除這些行。對於連接表,無論如何你都不可能有模型對象,所以它是唯一的方法。

有用資源: