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

About this user

Andy Vanasse

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Toggling associations for Many-to-Many relationships

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.

   1  
   2  def toggle_child_assoc(child_object)
   3      # check to see if the parent recognizes the collection_name
   4      collection_name = child_object.class.to_s.downcase.pluralize
   5      aCollection = self.send(collection_name) if self.respond_to?(collection_name)
   6      unless aCollection
   7        return false
   8      end
   9  
  10      # If the parent recognizes the collection_name then check to see if the child_object
  11      # appears in the collection.  If so then remove it, otherwise add it.
  12      if aCollection.include?(child_object)
  13        self.send("remove_%s" % collection_name, child_object)
  14      else
  15        self.send("add_%s" % collection_name, child_object)
  16      end
  17      true
  18  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.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS