开发者

Parent Model that can only have one child in Rails?

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 (Anothe开发者_JAVA百科r 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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜