ruby-on-rails – 如何删除嵌套的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回调吗? destroy和destroy_all有什么区别?我看过:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Delete+or+destroy%3F,差异仍然是模糊的. 解决方法
我是这样做的:
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关系,使用dependent :: destroy.这将导致在广告系列,日期和时间段的每个关联实例上调用destroy.要删除用户和时间段之间的关联,time_slot_users表中的记录,我添加了before_destroy回调.我使用了删除,因为可以在不创建对象实例的情况下删除这些行.对于连接表,无论如何你都不太可能拥有模型对象,所以这是唯一的方法. 有用的资源: > ActiveRecord Callbacks (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |