Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Toggling associations for Many-to-Many relationships (See related posts)

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)
    # 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.

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts