Question

Using class table inheritance it is recommended that the subclass refers to the superclass and not the other way around. Normally in Rails polymorphic associations work in the other direction--the super refers to the subclass.

Recommended

vehicle
  .id

car
  .vehicle_id # PK instead of using id (identity column)

boat
  .vehicle_id

Typical Rails polymorphic association

vehicle
  .id
  .subclass_type
  .subclass_id

car
  .id

boat
  .id

What I like about the recommended approach is that I can do away with having non-matching keys. That is, a given car and its vehicle super share the same id.

In my particular instance, I will potentially support multiple inheritance and so, for example, I could have a hybrid car-boat vehicle.

Questions:

  • How would you set up the ActiveRecord associations...

    • If a vehicle could have only one subclass?

    • If a vehicle could have many subclasses? (The problem I see here is that by not specifying a specific subclass_type how do the associations know which table to hit. I don't guess they would and so would have to hit all possible tables. So maybe an intersection table would help here.)

  • Is this a good design pattern for use with ActiveRecord or does it buck the Rails way enough that we should avoid it?

Was it helpful?

Solution

I opted for the simplest solution: using a polymorphic association (as shown in the second block). It will have better performance and be more maintainable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top