Skip to content

Commit d7103e6

Browse files
committed
Unscope includes when plucking linkage data
It's very common to eager load data in JR. But if we keep includes values when plucking for linkage data, it can make the query unnecessarily expensive. Let's use Post model for example: If we directly pluck all posts' `created_at` column, the query would be very simple ```sql SELECT "posts"."created_at" FROM "posts" ``` But if we keep includes values in the previous relation object, like ```ruby Post.includes(:author).pluck(:created_at) ``` It generates unnecessarily complicated query ```sql SELECT "posts"."created_at" FROM "posts" LEFT OUTER JOIN "people" ON "people"."id" = "posts"."author_id" ``` So we should always unscope includes when we only want to pluck linkage data.
1 parent eb0c74f commit d7103e6

File tree

1 file changed

+1
-0
lines changed

1 file changed

+1
-0
lines changed

lib/jsonapi/resource_serializer.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ def to_many_linkage(source, relationship)
410410
[obj.type.underscore.pluralize, obj.id]
411411
end
412412
else
413+
assoc = assoc.unscope(:includes) if assoc.is_a?(ActiveRecord::Relation)
413414
assoc.pluck(:type, :id).map do |type, id|
414415
[type.underscore.pluralize, id]
415416
end

0 commit comments

Comments
 (0)