DEV Community

Robin Vernon
Robin Vernon

Posted on

Let’s talk Relations

When getting started on a Ruby or Rails app, you may find that you have many tables that correlate. For example, let’s say we are making an app for a football team, this team plays in many games throughout the season but has their own stadium in their city. If we wanted to show the relation in a rails, we would use the macros in the Teams model:

Belongs_to

We can use this macro to state that the team belongs to a specific city. (Notice that city is singular)

Belongs_to :city

Has_many

We use this to show that the Football team participates in many games throughout the season. With this relation, we could call TeamName.Games.All and the console would return all games the team has participated in.

Has_many :games

Has_many. , through:
We can use this macro to show nested relations or relations that happen through an already associated relation.

Has_many :points, through: :games

Now if we seeded our DB to display points for each team(that would be a lot of instances), I would be able to call
TeamName.Points.All and the console would return the points from each game. This is because we now have access to points, through the games class.

Simple enough right? If you found this informative, I’d love to hear your feedback.
Check out my github to see how i use these macros:
https://github.com/robinlashae1

Top comments (0)