简体   繁体   中英

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?

可能有点晚了,但是在您的应用程序中有一个名为“模块”的模型会导致名称冲突的各种问题……

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM