Skip to content

Commit 43dfcd5

Browse files
authored
Optimize HABTM query (#73)
Could cause n+1 as the association table is joined, but not eager loaded.
1 parent 184d163 commit 43dfcd5

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

lib/jsonapi_compliable/adapters/active_record_sideloading.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,11 @@ def has_and_belongs_to_many(association_name, scope: nil, resource:, foreign_key
7676
parent_ids = parents.map { |p| p.send(primary_key) }
7777
parent_ids.uniq!
7878
parent_ids.compact!
79-
_scope.call.joins(through).where(through => { fk => parent_ids }).distinct
79+
_scope.call
80+
.joins(through)
81+
.preload(through) # otherwise n+1 as we reference in #assign
82+
.where(through => { fk => parent_ids })
83+
.distinct
8084
end
8185

8286
assign do |parents, children|

lib/jsonapi_compliable/version.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module JsonapiCompliable
2-
VERSION = "0.11.2"
2+
VERSION = "0.11.3"
33
end

0 commit comments

Comments
 (0)