def toggle_child_assoc(child_object) # check to see if the parent recognizes the collection_name 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 the parent recognizes the collection_name then check to see if the child_object # appears in the collection. If so then remove it, otherwise add it. 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.