Tutorial
Step 9: Polymorphic Resources
In the last step, we covered polymorphic relationships: a single relationship can point to many different Resources. Polymorphic Resources are the same concept, without an association: a single Resource can resolve to many different sub-Resources. It’s a very similar to Single-Table Inheritance in ActiveRecord.
To illustrate this, we’ll add a tasks
table and corresponding Task
superclass. Each record in this table will resolve to one of Bug
,
Epic
, or Feature
.
id | milestone_id | type | title |
---|---|---|---|
1 | null | Bug | Incorrect Value! |
2 | null | Feature | Build great stuff! |
3 | 1 | Epic | Build TONS of great stuff! |
Why not just stick with a single Task
model? Because each of these
types has specific behavior: only Feature
s have a points
attribute,
and only Epic
s have a milestones
relationship.
The Rails Stuff 🚂
Let’s create our Task
model:
And create models to reflect our STI logic:
Add the association:
Finally view the diff to edit your seeds.rb
file.
The Graphiti Stuff 🎨
Start by creating our Resource as normal:
Now edit to support polymorphism and associations:
The point of this was to show how responses could be specific to type,
so let’s customize Features
:
Only Epics have milestones, but let’s support those as well:
Digging Deeper 🧐
We can now resolve Tasks
, either as a relationship or through the
/tasks
endpoint directly. When Task
is type 'Feature'
it will have
an extra attribute of points
. When it’s an Epic
, it will have an
additional relationship Milestone
.
Graphiti is smart enough to fetch the appropriate relationships. A hit
to /tasks?include=milestones
will only query for milestones when the
resulting Task
records are Epic
s.