2013-04-30 74 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,因为可以在不创建对象实例的情况下移除这些行。对于连接表,无论如何你都不可能有模型对象,所以它是唯一的方法。

有用资源: