Skip to content

Commit

Permalink
Lookup polymorphic type from the column before the record (#1326)
Browse files Browse the repository at this point in the history
Currently, `Relationship#type_for_source` looks up polymorphic source's
type by:

1. Fetching its associated record.
2. Calling `.class._type` on that record.

This approach is inefficient because usually, a polymorphic record (the
`source`) has
`_type` and `_id` columns. And the `_type` column's value will be the
polymorphic relationship record's type.

So this PR makes `type_for_source` check the type value from column
before fetching the associated record.
  • Loading branch information
st0012 authored Jan 25, 2021
1 parent ad64f14 commit 20e051c
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/jsonapi/relationship.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,14 @@ def relation_name(options)

def type_for_source(source)
if polymorphic?
resource = source.public_send(name)
resource.class._type if resource
# try polymorphic type column before asking it from the resource record
if source._model.respond_to?(polymorphic_type)
model_type = source._model.send(polymorphic_type)
source.class.resource_for(model_type)._type if model_type
else
resource = source.public_send(name)
resource.class._type if resource
end
else
type
end
Expand Down

0 comments on commit 20e051c

Please sign in to comment.