Somewhere I Belong

Michael Gallipo
2 min readJun 25, 2018

One of the nice things about Ruby for a new developer is that while it has it’s moments of strange syntax (I am looking at you ||), generally it reads a lot like English. One of the areas this is clearest is when considering database table relationships.

There will be many times when you need to link data from one table in your database to that in another table. Some of the language associated with this — foreign keys and the like — can sound fairly esoteric. But the language used to connect your ruby models helps clarify the relationships — the terms “belongs to” and “has many.”

Database relationships can be either one to many or many to many. One to many is the easier of the two to code. Imagine you have a table of information on rental properties and also a table with data on owners/landlords. How do the relationships flow? In this case a landlord can own many different properties, but each property will have only one owner. In this case an owner “has many” rental properties and a rental property “belongs to” a landlord. In this case, the rental property table should contain a column for the landlord id (the foreign key). In the models section of your code, the landlord model would include “has_many :rental_properties” and the rental properties model would include “belongs_to :landlord”

In the case of a many-to-many relationship, you need to add a third table (called a join table) in order to establish the various relationships. The join table might consist of just the two foreign keys, but can also contain additional data. As an example, think of a high school athletic department. In this case each team will have many athletes, but at the same time athletes may play on many teams over the course of the year. Here, in addition to the Athlete table and the Team table, we would need a third table TeamAthlete (other names are possible, but mashing the two together is often the simplest and clearest). The TeamAthlete table will contain both an athlete_id column and a team_id column.

In the Athlete model you will have two lines of code.

has_many :team_athletes
has many :teams, through: :team_athletes

The Team model will look similar

has_many :team_athletes
has_many :athletes, through: :team_athletes

Finally, in the TeamAthlete model

belongs_to :athlete
belongs_to :team

Once those relationships are established, your app can now incorporate athlete information when working with the team data (printing a roster of players for example) and vice versa. If you’re ever in doubt about the nature of the data relationship, simply saying it out loud using the has many or belongs to terminology will point you in the right direction.

--

--