3

I have this model

class XmlImport < ActiveRecord::Base
   belongs_to :video
   belongs_to :user

   has_many :events, through: :event_import_records, dependent: :destroy
   has_many :event_import_records, dependent: :destroy

   has_attached_file :xml
   validates_attachment_content_type :xml, :content_type => ["text/xml"]
end

The :event_import_records entries are being destroyed. But the :events are not.

  • Is the dependent:destroy on the has_many through association valid?
  • Is there another way of writing it? If that is not correct
  • How can I destroy all the events associated to the XmlImport through the event_import_records?
limoragni
  • 2,716
  • 2
  • 32
  • 50
  • this is what i found, hope it's helpful [link](http://stackoverflow.com/questions/1399394/dependent-destroy-on-a-has-many-through-association) – Firyn Mar 28 '15 at 00:26
  • I've read that one, but in that question the problem he had was the one I've already solved! Thanks anyway! – limoragni Mar 28 '15 at 02:06

1 Answers1

1

You can find at the Rails API that: "If using with the :through option, the association on the join model must be a belongs_to, and the records which get deleted are the join records, rather than the associated records." I understand that it delete the joins records but not the associated by through.

If I were you, I try:

class EventImportRecord < ActiveRecord::Base
  has_many :events, dependent: :destroy
end

If not work I swap the order of the has_many relations on the XmlImport model, because of "Note that :dependent is implemented using Rails' callback system, which works by processing callbacks in order. Therefore, other callbacks declared either before or after the :dependent option can affect what it does." Also find at the same page of the Rails API.

Alejandro Babio
  • 5,189
  • 17
  • 28