Creating a table with multiple associations

January 18, 2016

Fight Schema

In true Turing fashion, we were assigned a mini-Rails project with three days to complete it. My pair Aaron Greenspan and I decided we would create an app where users were Dojo leaders and they could log in to keep track of their combatants. Admins would be able to set up fights between combatants and users would be able to see a newsfeed of their victories and defeats. The dojo leader would initialize their combatants with certain skills, D&D style.

We needed a way to store the results of the fights, and after some deliberation, we chose to set up a fights table that would have multiple associations to the same model. That way, for each fight, we could store the ids of the winning combatant and the losing combatant in one row, instead of having two records for one fight. You can see the schema for this design above.

ActiveRecord has a way to implement this, and thanks to this excellent blog post and this StackOverflow post we got it set up in our models like this:

Normally ActiveRecord assumes the class_name, but you can specify it and the foreign_key, and then name your association whatever you want. Here in the combatants model we’ve name the association "winning_fights", specified the class_name: "Fight" and the foreign_key: "winning_combatant_id". Notice in the Fight model that association names are the same as the foreign key that connects them.

For our newsfeed, this association set-up makes it very easy to list the victories and defeats of a particular dojo in our view:

You can see our whole project here. Remember we only had three days...

...back to posts