0

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?

Community
  • 1
  • 1
Mario
  • 6,572
  • 3
  • 42
  • 74
  • Rails, and thus ActiveRecord, is opinionated software. You class table inheritance is not part of that opinion. I think you're better off with STI and/or dynamically using modules into your Vehicle class. – Ariejan Oct 03 '09 at 17:52

1 Answers1

0

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.

Mario
  • 6,572
  • 3
  • 42
  • 74