Difference between sti and polymorphic associations

August 27th, 2006

Ok. I’ve been struggling with a modelling problem all day. I had just started investigating Polymorphic Associations in rails for the first time, and they seemed to me to be used to do the same thing in a lot of cases. I couldn’t quite work out the pros and cons of using one vs. the other.

#rubyonrails to the rescue:

[10:57pm] gmcinnes: nzkoz: well say I have a class Response and I want child classes like TextResponse, MultipleChoiceResponse etc. Seems I could do that with STI, but also with Polymorphic Associations
[10:59pm] nzkoz: gmcinnes: no, polymorphic associations are about references to an abtract type, or ‘interface’. i.e. this thing can be taggable
[10:59pm] nzkoz: STI is for inheritance, i.e. these things are responses
[10:59pm] gmcinnes: nzkoz: I thought so, but my abstract interface could be Response, no?
[11:00pm] nzkoz: with polymorphic associations you’re localising the abstraction to that association
[11:00pm] nzkoz: STI means the abstraction applies everywhere
[11:00pm] gmcinnes: nzkoz: Ah ha!
[11:00pm] nzkoz: so if your various things are only the same in that they relate to something, then use the polymorphic assoc
[11:01pm] gmcinnes: nzkoz: bingo. I’ve been reading on and off all day and nothing crystalized it like that line. Thank you.
[11:02pm] nzkoz: gmcinnes: heh, no problem. Just remember that abstractions rarely apply cleanly all over. so the polymorphic asssociations are probably more likely to work for you, they’ll be more flexible too
[11:04pm] yawn: gmcinnes: it’s much more complicated to maintain referential integrity checks on database level (compared to STI where it’s trivial)
[11:04pm] yawn: gmcinnes: IF that’s relevant to you
[11:05pm] gmcinnes: yawn: it’s not Fortunately.
[11:06pm] micahf: Reloadable?

programming, ruby on rails | Comments | Trackback Jump to the top of this page

One comment on “Difference between sti and polymorphic associations”

  1. 01

    That was very, very helpful! Thanks for publishing it.

    Conrad at May 28th, 2007 around 1:14 am
    Jump to the top of this page

Leave a Reply

  •  
  •  
  •  

You can keep track of new comments to this post with the comments feed.

Recently on Flickr

    mull - 21.jpgmull - 20.jpgmull - 19.jpgmull - 18.jpg

Recently Listened

Meta

The Carousell