Tutorial
Step 8: Polymorphic Relationships
Let’s introduce the concept of a Note. A Note can belong to a Department, an Employee, or a Team. For this, we’ll need to introduce the concept of polymorphism.
id | notable_id | notable_type | body |
---|---|---|---|
1 | 1 | Employee | A Sample Note! |
2 | 1 | Department | Another Sample Note! |
3 | 1 | Team | A Third Sample Note! |
The Rails Stuff 🚂
Make sure to add the corresponding model relationships:
Finally, make sure to edit your seed file - check out the diff to see the necessary adjustments.
The Graphiti Stuff 🎨
Let’s create our NoteResource
:
And corresponding associations:
Digging Deeper 🧐
When defining a polymorphic relationship for our API, we’re saying “grab
all the parent records, group them by a type
column, and execute
different queries for each type”. This way records with notable_type ==
'Employee'
can hit the employees
table, but records with
notable_type == 'Department'
could in theory load from a different API
altogether.
Each of the on
lines defines a new belongs_to
association. That
means you can customize just like always: