Rails HABTM – Properly removing an association

According to the Rails documentation:

collection.delete(object, …)

Removes one or more objects from the
collection by removing their associations from the join table. This
does not destroy the objects.

Brilliant reference here for you

You can use:

product = Product.find(x)
special = product.specials.find(y)

product.specials.delete(special)

This creates ActiveRecord objects for both the object you’re trying to remove, which gives clear definition to the function

collection.clear

Removes all objects from the
collection by removing their associations from the join table. This
does not destroy the objects.

In this example:

product = Product.find(x)

product.specials.clear

Leave a Comment