The Has_Many:Through Dilemma.

Andrew Lahr
2 min readMar 7, 2021

--

I recently completed the second phase of my flatiron school curriculum. And wouldn’t you know it— there was a big ol’ project standing in between me and phase 3.

One of the fundamental principles in understanding ActiveRecord (or any database tool, for that matter) is the has_many:through relationship. And because my project — a video game review website for classic real time strategy(RTS) games — would require just such a relationship, I thought I would talk about how this concept can be confusing to newbies such as myself.

I knew that my website needed three classes. A User class, a Game class, and a Review class. But because I thought that a user would have to own a game, I mistakenly believed that a user would have many games, and subsequently, have many reviews through those games…I was WRONG!

As it turns out, you have to think differently about object relationships when building a website.

Yes, a user technically should own a game before reviewing it on a website. What I neglected to understand was that the the games themselves also needed to be the owner of each review made by a user. So rather than a user having many games and a game having many users (and thus a user having many reviews through games), both the user and the game have many reviews, and are JOINED by their specific reviews.

In my case, the reviews table was my single source of truth, a concept that basically means you should only have one table that includes the information you need to assocaite with its parents

Here’s a visual representation of my three classes and ActiveRecord associations:

After a long evening of database-centric meditation, I was able to build and migrate the above tables, and in doing so, came one step closer to fully understanding object relationships and join tables.

If you happen to be struggling with the has_many:through relationship, just know that it is absolutely normal to be confused, or even downright ignorant of how your table relationships should be built, especially as more and more variables get added to the equation.

If you’re looking for more information, head on over here, where you’ll find some sweet, sweet, information on table joins.

And with that I say adieu. Happy coding, folks!

--

--

Andrew Lahr
Andrew Lahr

Written by Andrew Lahr

Former copywriter and aspiring software engineer. Open to both coding and writing opportunities.

No responses yet