Skip to content

Commit 20e051c

Browse files
authored
Lookup polymorphic type from the column before the record (#1326)
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.
1 parent ad64f14 commit 20e051c

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

lib/jsonapi/relationship.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,14 @@ def relation_name(options)
5555

5656
def type_for_source(source)
5757
if polymorphic?
58-
resource = source.public_send(name)
59-
resource.class._type if resource
58+
# try polymorphic type column before asking it from the resource record
59+
if source._model.respond_to?(polymorphic_type)
60+
model_type = source._model.send(polymorphic_type)
61+
source.class.resource_for(model_type)._type if model_type
62+
else
63+
resource = source.public_send(name)
64+
resource.class._type if resource
65+
end
6066
else
6167
type
6268
end

0 commit comments

Comments
 (0)