Currently in one my project, I ran into an interesting association problem that I’d previously not dealt with before. Which is specifying different kinds of associations for the same model.
You’re probably saying “Wait whaaaa…?”. Don’t worry, I can relate because that’s exactly what I said. So let’s lay out an example scenario and see how we can approach solving it:
So in this example, we have two simple models;
Production. The only associations ever made is between the production and the actor, however a production can have many types of actors such as
So why not just create an STI and have different types of actors?
Well it’s not quite that simple because an actor will not always be a leading actor. An actor can be a leading role on one production, but a supporting role on another. So in order to solve this issue, we must approach it from the association side of things. Here’s what I came up with after about an hour of playing around with different options:
Here our production has both lead and supporting actors due to a
through relationship, we are also specifying through
source: :actor that both associations are towards the
source is an argument for an ActiveRecord association that specifies the model being associated to from the through model, if the name of the association is not the same as the name of the associated model. Read more about it here.
Back to the topic at hand, we can now also query the lead and supporting performances of our actors because of the same
through relationship that connects the two models, and we will know that
supporting_performances will return the actual production because we once again specified that through the
And thats it! Now we have two models that can be associated with each other in multiple different ways and names; achieved by specifying the through models and the source model of the association.