The Rails 4 documentation says this regarding destroy callbacks on the join
model for a has_many :through relationship:
collection=objects Replaces the collections content by deleting and adding
objects as appropriate. If the :through option is true callbacks in the
join models are triggered except destroy callbacks, since deletion is
Thankfully it's documented at least, but I want to know why on earth this
is the case? It makes more sense to trigger destroy callbacks (or have the
option to) on a :through since these types of models can have destroy
callbacks and other associations.
In my case I had a has_and_belongs_to_many relationship on the join tables
model off to another model. The records on that second join table would
never be deleted when the associated records on the first join table were
deleted. I resorted to this which feels hacky, and I have to repeat myself
on each side of the :through relationship:
class SchoolsTemplate < ActiveRecord::Base
class School < ActiveRecord::Base
has_many :schools_templates, dependent: :destroy
has_many :templates, through: :schools_templates, before_remove: :remove_groups_school_templates
schools_templates.where(template: template).first.groups.clear end
There's a validation to 'ensure' uniqueness on the join tables records
between the two foreign keys, so that's why I can call first in the
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firstname.lastname@example.org.
To post to this group, send email to email@example.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/6afe728a-9585-4431-bc96-71f6f8ceaeeb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.