Polymorphic, Self-Referential ActiveRecord Associations
Posted by Daniel Butler Sat, 20 May 2006 23:39:00 GMT
Jason King and Josh Susser had an interesting conversation about how to use ActiveRecord to achieve Polymorphic, many-to-many, self-referential associations on the Ruby on Rails mailing list. Jason describes his problem domain as having a:
Container which can contain one or more Element. An Element is a polymorph of either a Container or a Chunk. An Element can exist in one or more Containers. I use a table called ownerships as the join between Containers and Element.
Josh Susser, author of the has_many :through blog, attempts a solution. He describes his trick, "You have to disambiguate the two different associations to containers—one way is as your container, and the other is as an element. That means you need different names for those relationship. I chose "owner" to indicate an element's container from the element's perspective. You also have to use a different name for the two kinds of ownerships, containing and contained."
Read on for the final coded solution.
Read more...
