1

Sorry the title is pretty unclear - I'm just not quiet sure how to phrase the question without explaining it.

I would like to record workouts with my app. I would like a Workout Table (what I'm calling the parent) that has basic information like date and sub_workout_type_id

A workout record can have either a Cardiovascular workout (One Model) or a Strength Workout (Another Model).

My thought on have 3 tables instead of just the 2 Cario Workout model and strength workout model is that I would be able to pull a feed of any type of workout, by pulling the Workout Records and then dig deeper as needed.

Perhaps there is a more ruby-ish way to do this? Because right now I don't know of a way to say has_one_model_or_the_other. Thanks!

Rapture
  • 1,876
  • 10
  • 23
  • 42

2 Answers2

2

I see two options, either you use STI (single table inheritance) : in that case you would have a single table that would be able to contain both a cardiovascular model or a strength workout, and a type. This would only work if the two models share some common characteristics.

Another solution is to write something like

has_one :cardiovascular
has_one :strength

and then use validations to enforce that only one of them is set.

Hope this helps.

nathanvda
  • 49,707
  • 13
  • 117
  • 139
  • I love the idea of using STI - I had no idea this was available. One question I have is about performance. Let's say cario has 25 fields and strength has 25 - would you foresee the queries taking longer or being less efficient in one table? Also, can I write migrations for each type like I would a normal model? Or do can I only write migrations for the Workout? Sorry for 2 questions in 1 comment! – Rapture Sep 21 '11 at 19:48
  • The efficiency difference probably wouldn't be noticeable, but it'd be easy enough to find out some real-world numbers. Migrations aren't model-specific--any migration can contain any info, for any table, for multiple tables, etc. – Dave Newton Sep 21 '11 at 21:31
  • Thanks @DaveNewton for clearing that up. I'll give it a shot! – Rapture Sep 21 '11 at 22:08
0

As mentioned by @nathanvda, STI could be a good choice.

If you're looking to store class specific data with your models, maybe check out Modeling inheritance with Ruby/Rails ORMs to see if that answer gives you any ideas on how to model this relationship.

Note, the example there uses has_many's but a lot of the ideas are similar.

Community
  • 1
  • 1
Kristian PD
  • 2,705
  • 1
  • 19
  • 22