0
votes

I have a Change model that utilizes single table inheritance that has the following attributes:

id
type    #this is a single table inheritance type field.
description
dynamic_id

I also have two sub classes, Race which is a subclasses of Change and Workout which is a sub class of Race.

class Race < Change

end

class Workout < Race

end

I have a fourth class called Track and I'd like to create the following four associations by just using the dynamic_id field in the Change object. (i.e. I have not explicitly added race_id and workout_id to the Change table. Instead I want to use the dynamic_id as the race_id for the Race class and the dynamic_id as the workout_id for the Workout class) By doing this, I will avoid having a lot of nil fields in my database.)

Here are the four associations I'm trying to create.

  1. Race Model - belongs_to :track
  2. Workout Model - belongs_to :track
  3. Track Model - has_many :races
  4. Track Model - has_many :workouts

I've been trying to accomplish this with associations using :class_name and :foreign_key, but I can't seem to get it working. Is this actually possible. I realize its probably not a best practice, but I'd still like to see if it doable. Thanks for your input.

1

1 Answers

2
votes

What you are looking for are "polymorphic associations". You can find more in the rails guides: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Your case is a bit special because you want to use polymorphic associations with STI. I remember that there was a bug with this combination but it could be fixed by now.

I did not read it completely but this blog post seems to describe the situation: http://www.archonsystems.com/devblog/2011/12/20/rails-single-table-inheritance-with-polymorphic-association/

The problem I encountered with polymorphic associations and STI is described here: Why polymorphic association doesn't work for STI if type column of the polymorphic association doesn't point to the base model of STI?