I have a rather greedy object that needs to be associated with most of the other objects in my domain. To compensate, I've written the following code to take care of toggling the association (adding a record in the join table if it does not exist or removing it if it does). I've called it toggle because it's physically represented by toggling the state of a checkbox on a form.
def toggle_child_assoc(child_object)
collection_name = child_object.class.to_s.downcase.pluralize
aCollection = self.send(collection_name) if self.respond_to?(collection_name)
unless aCollection
return false
end
if aCollection.include?(child_object)
self.send("remove_%s" % collection_name, child_object)
else
self.send("add_%s" % collection_name, child_object)
end
true
end
First the code determines if the "parent" of the association actually supports a collection of the child object's class by testing to see if it responds to the method corresponding to the name of the collection. If not the method returns false. Otherwise, the method checks to see if the parent object already has the child in its collection. If it does it builds a call to remove_collection_name to remove it and if it does not it builds a call to add_collection_name to add it.
The code could be improved by adding a means by which to override the collection_name. This override would be used in the event that the child is a subclass of a class with which the parent has a habtm relationship.