Skip to content

Commit 1264f13

Browse files
When loading link for polymorphic relationship, don't use AR pluck if data already present
1 parent 1470c27 commit 1264f13

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

lib/jsonapi/resource_serializer.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,8 +306,16 @@ def foreign_key_value(source, relationship)
306306
def foreign_key_types_and_values(source, relationship)
307307
if relationship.is_a?(JSONAPI::Relationship::ToMany)
308308
if relationship.polymorphic?
309-
source._model.public_send(relationship.name).pluck(:type, :id).map do |type, id|
310-
[type.underscore.pluralize, IdValueFormatter.format(id)]
309+
assoc = source._model.public_send(relationship.name)
310+
# Avoid hitting the database again for values already pre-loaded
311+
if assoc.respond_to?(:loaded?) and assoc.loaded?
312+
assoc.map do |obj|
313+
[obj.type.underscore.pluralize, IdValueFormatter.format(obj.id)]
314+
end
315+
else
316+
assoc.pluck(:type, :id).map do |type, id|
317+
[type.underscore.pluralize, IdValueFormatter.format(id)]
318+
end
311319
end
312320
else
313321
source.public_send(relationship.foreign_key).map do |value|

0 commit comments

Comments
 (0)