How Relationships Work in Rails

Elizabeth
2 min readDec 24, 2020

--

On any rails app inside of your database you will find a schema page labeled schema.rb. That schema page will only be filled when your migrations are complete. Below is a common migration, user, in this example below user has a first name, last name, password, bio, email and of course bank number. To begin your migration type ‘rails g resource user’ into the terminal. This will prompt your rails app to create a controller and below user table, which you will then fill in with the data needed on each user instance.

What does each migration have to do with another, you may ask? Well that is where relationships come in. Each user has many posts, each post has many comments, and each comment has many likes and dislikes. How do all the these instances of likes know which comment they below to? How does each post know its owner? That is where relationships come in, and the reason I started this blog mentioning your schema page.

Schema page for my Etsy clone project.

Each instance is given an item ID without the creator specifying an ID. Therefor if one person has many posts, each post will know its creator by their user ID. User does not have to know its posts IDs, only posts have to know their creator’s ID. As SQL tables are much like an excel sheet, meaning they cannot hold an array for one of the values.

SQL table example.

Similarly, if two tables have a many to many relationship, for example above item history has many user views and users have many viewed items, we set up a third table to keep track of each connection. This data table can simply hold user_id and item_id.

Quick reminder to create a rails project using PostgreSQL, simply type the above into your terminal.

Happy coding!

--

--

Elizabeth
Elizabeth

No responses yet