DEV Community

Cover image for Multi-Relational Models in Ruby, how to use 'includes' to your advantage.
Katie Clark
Katie Clark

Posted on

Multi-Relational Models in Ruby, how to use 'includes' to your advantage.

For my Charity Organizer project, that I completed through Flatiron's Coding Bootcamp, I truly learned the in's and out's of Ruby's relationship models. The project involved four relational tables: User, Charity, Favorites and Donations. At the time, I thought 'yes it's one more than usual, but how crazy can it get?'. Right?, Wrong. I searched high and low through Google and even had an instructor help me determine what the correct syntax was for connecting one of my models. I wanted to share with you my findings so that hopefully, in the future, this will help someone much faster than the hour+ of digging I needed to do for a simple line of code.

First, I'm going to show you my models to better explain the relationships between all of the classes.

User:
Alt Text

Charity:
Alt Text

Favorite:
Alt Text

Donation:
Alt Text

The User and Charity models have slightly more complex relationships than I had encountered before, which made it difficult when determining how to use 'includes' in my Controllers. Specifically, my Favorites Controller. I wanted a user to be able to create a Favorite of a Charity and then add/post donations to said Charity on their own personal page. This became difficult because Favorites and Donations are not linked in any direct way, so it was not just a simple 'includes' statement. I had to include the Charity class and through the Favorites class, access the Donations class. Which I thought would be simple to find information on, right? I mean how many large-scale corporations have multi-relational databases, if not all? This proved more difficult than I had anticipated and after an hour of searching(and really only playing around with the syntax), this is what finally worked:

Alt Text

Additionally, this is what I used for my Charities Controller:
Alt Text

This finally enabled me to access the props in my frontend React application and made my project work! I hope this helps any of you in the future in connecting multiple databases using Rails. Happy coding!

Top comments (0)