Rails: Models that inherit columns from parent, and each have additional columns

760 views Asked by At

I'm creating a logbook app that will work for multiple sports (e.g. scuba-diving and sky-diving) and I'm trying to find a way to have children models inheriting not only parent methods, but parent (database) columns.

An image may explain better: Logbook database sample

So, any models under the category ScubaDiving, FreeDiving and SkyDiving are models that I will be calling from the views.
The models under Parent or Diving however, will never be called, and are only meant to populate their children with database columns (and methods perhaps).

What is the best way to go about creating the models + associations + inheritance ?

From the research I've done, I've read about:

  1. Single Table Inheritance:
    • Will only pass parent methods, not database columns
  2. Polymorphic Associations:
    • I compared my situation to the example I found (comments on photos, articles, posts), but my Divespot and Airport (equivalent: Photo, Article) can't have many Spots (eq: Comments).
  3. Multiple Table Inheritance:
    • Couldn't make it work, but it seemed the closest to what I was looking for?
  4. Simple models:
    • I could always create a model for each child (with no parent) and repeat the code. I still wanted to see if there was a way to refacto.

I am using Rails 5 and a PostGresql database.

1

There are 1 answers

1
tbreier On BEST ANSWER
  1. Single Table Inheritance:
    • Will only pass parent methods, not database columns

Of course all classes inherit the database columns. Since all classes "live" in the same table, they have the same columns. STI is probably not the best solution in your case for another reason - the columns seem to be different for each model, so you would have a bunch of columns being "NULL" for the models that don't have these columns.

I'd suggest considering to create a model / table for each of your classes and then linking the children objects to an object representing the parent. You can then delegate methods like name, location to the Spot, for example. You will probably then need to work with polymorphic associations. You can be a bit fancy and try "proper" MTI, see this guide