Upon closer inspection, the HABTM relationships should delete the join table entries. However, neither the HABTM relationship nor the relationship that I described in the original version (see Message History) of this solution deletes these entries in the connection table when you delete an entry using the delete method. ActiveRecord::Base#delete does not call any callbacks, such as HABTM relationships, that are set to remove orphaned entries from the connection table. Instead, you should use ActiveRecord::Base#destroy .
You will need to use raw SQL to remove unnecessary records. If you decide to create a join model, you can iterate over the records in the join model, deleting them without association.
Example:
class Foo < ActiveRecord::Base has_many :foo_bars, :dependent => :destroy has_many :bars, :through => :foo_bars end class FooBar < ActiveRecord::Base belongs_to :foo belongs_to :bar end class Bar < ActiveRecord::Base has_many :foo_bars, :dependent => :destroy has_many :foos, :through => :foo_bars end FooBar.all.each{|fb| fb.destroy? if fb.foo.nil? || fb.bar.nil? }
source share