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:
$ bin/rails g model Department name:stringTo add the foreign key to positions:
$ bin/rails g migration add_department_id_to_positionsclass AddDepartmentIdToPositions < ActiveRecord::Migration[5.2]
def change
add_foreign_key :positions, :departments
end
endUpdate the database:
$ bin/rails db:migrateUpdate our seed file:
[Employee, Position, Department].each(&:delete_all)
engineering = Department.create! name: 'Engineering'
safety = Department.create! name: 'Safety'
qa = Department.create! name: 'QA'
departments = [engineering, safety, qa]
100.times do
employee = Employee.create! first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name,
age: rand(20..80)
(1..2).each do |i|
employee.positions.create! title: Faker::Job.title,
historical_index: i,
active: i == 1,
department: departments.sample
end
endMake 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:
factory :position do
employee
department
# ... code ...
endThe Graphiti Stuff 🎨
You should be used to this by now:
bin/rails g graphiti:resource Department name:stringAdd the association:
# app/resources/position_resource.rb
belongs_to :departmentAnd 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:
/departments?filter[id]=1Which we get out-of-the-📦
But remember, you can customize these relationships just like the
previous has_many section.