So this is probably a fairly easy question to answer but here goes anyway.
I want to have this view, say media_objects/ that shows a list of media objects. Easy enough, right? However, I want the list of media objects to be a collection of things that are subtypes of MediaObject, CDMediaObject, DVDMediaObject, for example. Each of these subtypes needs to be represented with a db table for specific set of metadata that is not entirely common across the subtypes.
My first pass at this was to create a model for each of the subtypes, alter the MediaObject to be smart enough to join into those tables on it’s conceptual ‘all’ behavior. This seems straightforward enough but I end up doing a lot of little things that feel not so rails-O-rific so I wanted to ask for advice here.
I don’t have any concrete code for this example yet, obviously, but if you have questions I’ll gladly edit this question to provide that information…
thanks!
Creating a model for each sub-type is the way to go, but what you’re talking about is multiple-table inheritance. Rails assumes single-table inheritance and provides really easy support for setting it up. Add a
typecolumn to yourmedia_objectstable, and add all the columns for each of the specific types of MediaObject to the table. Then make each of your models a sub-class ofMediaObject:Rails will handle pulling the records out and instantiating the correct subclass, so that when you
MediaObject.find(:all)the results will contain a mixture of instances of the various subclasses ofMediaObject.Note this doesn’t meet your requirement:
Rails is all about convention-over-configuration, and it will make your life very easy if you write your application to it’s strengths rather than expecting Rails to adapt to your requirements. Yes, STI will waste space leaving some columns unpopulated for every record. Should you care? Probably not; database storage is cheap, and extra columns won’t affect lookup performance if your important columns have indexes on them.
That said, you can setup something very close to multiple-table inheritance, but you probably shouldn’t.