Rails: Delete associated records on object destroy
activerecord, ruby-on-rails, ruby-on-rails-3, ruby-on-rails-4
Solution
The options `dependent: :destroy` is ignored when using with the `:through` (see doc). You have to do it manually, with a `after_destroy` callback for example.
class Deal
after_destroy :destroy_coupon_codes
private
def destroy_coupon_codes
self.coupon_codes.destroy_all
end
end
Problem
I have 2 models ``` class Deal < ActiveRecord::Base has_many :couponizations, dependent: :destroy has_many :coupon_codes, through: :couponizations, source: :coupon_code, dependent: :destroy accepts_nested_attributes_for :coupon_codes, allow_destroy: true end ``` and ``` class CouponCode < ActiveRecord::Base has_one :couponization, dependent: :destroy has_one :deal, through: :couponization, source: :deal ``` which are linked by many-to-many relationship ``` class Couponization < ActiveRecord::Base belongs_to :coupon_code belongs_to :deal end ``` Despite I specified `dependent: :destroy` option, when I delete deal, coupon codes are not being deleted. However couponizations are deleted successfully. Is there any way to delete associated nested records on object destroy?