Tutorial
Step 3: Belongs To
We’ll be adding the database table departments
:
id | name |
---|---|
1 | Engineering |
2 | Safety |
3 | QA |
We’ll also be adding a department_id:integer
foreign key column to
the positions
table.
The Rails Stuff 🚂
Generate the Department
model:
To add the foreign key to positions
:
Update the database:
Update our seed file:
Make sure to update spec/factories/departments.rb
with randomized
data. Then, since this is also a required relationship, update
spec/factories/positions.rb
to always seed a department when we ask to
create a position:
The Graphiti Stuff 🎨
You should be used to this by now:
Add the association:
And review the end of Step 2 to get all your specs passing (add the department to the request payload). Practice makes perfect!
Digging Deeper 🧐
Note that we didn’t need a filter like we did in step two. That’s
because the primary key connecting the Resources is id
by
default. In other words, the Link would be something like:
Which we get out-of-the-📦
But remember, you can customize these relationships just like the
previous has_many
section.