kolrie
kolrie

Reputation: 12732

How do I model a polymorphic has_many relationship in Rails 3

Imagine I have a model called Course and each course has_many Modules. However I want the modules to be a different range of types.

For instance, the Module model would be the parent class and would have two fields: title and description that will be common amongst all types of children.

Now I need Course to be able to have any number of Slideshow, Video, Image, Text instances, however they must be retrieved through Course#modules.

Consider that each child class type has its own attributes, like Video could have an url field, whereas Text could have contents, for instance.

What's the right way to model this association?

Upvotes: 0

Views: 195

Answers (2)

Jules Copeland
Jules Copeland

Reputation: 1722

It might be a bit late, but having a model in your application called 'Module' will cause all sorts of problems with name collisions...

Upvotes: 1

mliebelt
mliebelt

Reputation: 15525

I think there are 2 options (possibly combined):

  • Use polymorphic associations (see "Polymorphic Associations" for an example). Your migration should look like:

    create_table :courses do |t|
      t.references :modules, :polymorphic => {:default => 'Text'}
    end
    
  • Use Single-Table Inheritance: There your models are subclassed from a common base class, and this is realized on the database by only one table that contains all columns for all model classes.

Have a look at "Alex Westholms Blog" about the 2, and the comparison. I think you should go with polymorphic associations, because your modules have a lot of different attributes.

Upvotes: 0

Related Questions