How to remove an entry from the HABTM junction table in rails?

In many testing iterations, I noticed that my connection table, representing the HABTM relationship between two models, does not delete records when instances of these models are deleted. Do I need to do something special when deleting an instance of a model with HABTM relationships?

+4
source share
2 answers

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? } 
+7
source

Entries in the connection table should be deleted if you are not doing anything. You can add the :delete_sql parameter to your code to change the behavior if you have a strange situation. Removing an object on the other side of the connection is not the default behavior.

0
source

All Articles