0
votes

I'm learning Rails and currently working on my first application.

I have a Chapter that has_many Activities. There are different types of activities and they all have very different attributes. I have a base Activity and different subclasses to represent each activity type.

I'm having issues modeling this scenario without using STI (since I don't want a single table with many null columns). I read about polymorphic associations but I'm not sure how to use this feature to model this situation (I'm not even sure if this scenario is a good fit for polymorphic associations).

Has anyone modeled something like this using this feature?

1
Why not use a json field to keep theses different attributes? If you no want choose this, show your DER and let me see what I can do for you. - thiaguerd
If activities all have very different attributes, I would not use STI and Polymorphic. That is to say, I would not make activities inherit from a base activity. I would make a concern for common methods of activity and include it in each activity class. However, it will be better for getting a solution if you can post more info. - Feifei Xiong

1 Answers

0
votes

If you have one table for each activity type, you can do the following :

  • Create one class per activity type. They all have to inherit from ActiveRecord::Base
  • Implement common activity behavior in a module and include this module every activity class.
  • Use a belongs_to :chapter relation in every activity class
  • Use one has_many relation per activity class in the chapter class

If you need helpers to access all activities at once from a chapter, you will have to implement it by yourself with a SQL union for instance.