DEV Community

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

Posted on

1 1

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!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay