Rails 3.0 Best Practices: Multiple Subtypes of a Model Object

So this is probably a pretty simple question to answer, but it doesn't matter here.

I want to have this view, for example media_objects /, which shows a list of media objects. Easy, right? However, I want the list of media objects to be a collection of objects that are subtypes of MediaObject, CDMediaObject, DVDMediaObject, for example. Each of these subtypes must be represented by a db table for a specific set of metadata that is not completely common to all subtypes.

My first pass on this was to create a model for each of the subtypes, modify MediaObject to be smart enough to join these tables in conceptual “all” behavior. It seems simple enough, but I end up doing a lot of little things that are not so rails-o-rific, so I wanted to ask for advice here.

I don’t have specific code yet for this example, but if you have any questions, I will gladly edit this question to provide this information ...

thank!

+5
source share
3 answers

- , , , - . Rails . type media_objects MediaObject . MediaObject:

class MediaObject < ActiveRecord::Base

end

class CDMediaObject < MediaObject

end

Rails , MediaObject.find(:all), MediaObject.

, :

db , .

Rails - , , , , , Rails . , STI , , . ? ; , , .

, - , , , .

+7

, : , - , db TEXT, "_". .

, "media_objects", " : ". CDMediaObject, DVDMediaObject ..

- MongoDB ( MySQL), . . .

0

, , , - .

If the DB is postgres, I would suggest using STI along the hstore column to store attributes that are not common to different objects. This will avoid losing space in the database, but attributes may be available for different operations.

0
source

All Articles