Forum: Ruby on Rails Polymorphic Associations or not

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
495540c5659cc7ebe690ac775ed2b098?d=identicon&s=25 Rob (Guest)
on 2007-01-27 22:07

I am starting my store application again for the 3rd time, I am just
trying to get eveything right so that I don't come up with any more
complex problems later. Hopefully someone can steer me in the right

I have a store that sells lots of types of product.

e.g. CDs, T-Shirts, DVD

Each product type has different associations.

Cds - multiple artists, multiple genres, multiples record labels
T-Shirts - one artist
DVD - one artist, one video format (NTSC, PAL)

My problem is that while these product types and have different
characteristics are all still products, I am wondering if there is any
benefit in using Polymorphic Assocations to link these all together as
Products or if I have misunderstood the reasons for using them in the
first place. I have read a link that recommends them for this but
nothing to demonstrate this actually in practice by anyone.

I wonder if, when I have actually been able to implement this I will be
able to use them like so

artist = Artist.find(1)
artist.products.each do |p|
  blah blah blah

To be honest many of the explanations I have read on Polymorphic
Associations have left me a little bewildered. I am sure once I get them
working the concept won't seem so alien.


F5c118aaeb5bb7162db613a37e595be8?d=identicon&s=25 Mick Sharpe (micksharpe)
on 2007-01-28 06:16
I have a similar problem to you with my application needing to hold
different product types with different attributes. My next big push is
to switch from single-table inheritance to polymorphic associations and
I would say that polymorphic associations are definitely the way to go.
Arm yourself with some good books, read the relevant sections and then
plug away.

You will only be able to use artist.products if the artist information
(id) is stored in the products table. Since CDs can have multiple
artists, this may be difficult to arrange. If you are unsure about how
to organise your data structures, why don't you create a class diagram
for your entire application and put it up for review?
This topic is locked and can not be replied to.