Skip to content

Commit ec703d7

Browse files
committed
Properly normalize scopes as keys
1 parent 5ade1a7 commit ec703d7

3 files changed

Lines changed: 32 additions & 0 deletions

File tree

lib/graphql/dataloader/active_record_association_source.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ def initialize(association, scope = nil)
1212
@scope = scope
1313
end
1414

15+
def self.batch_key_for(association, scope = nil)
16+
if scope
17+
[association, scope.to_sql]
18+
else
19+
[association]
20+
end
21+
end
22+
1523
def load(record)
1624
if (assoc = record.association(@association)).loaded?
1725
assoc.target

spec/graphql/dataloader/active_record_association_source_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,29 @@
126126
assert_includes log, 'WHERE "albums"."id" = ? [["id", 3]]'
127127
end
128128

129+
it_dataloads "works with collection associations with scope" do |d|
130+
wilco = ::Band.find(4)
131+
chon = ::Band.find(3)
132+
albums_by_band = nil
133+
log = with_active_record_log(colorize: false) do
134+
one_month_ago = 1.month.ago.end_of_day
135+
albums_by_band_1 = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :albums, Album.where("created_at >= ?", one_month_ago)).request(wilco)
136+
albums_by_band_2 = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :albums, Album.where("created_at >= ?", one_month_ago)).request(chon)
137+
albums_by_band = [albums_by_band_1.load, albums_by_band_2.load]
138+
end
139+
140+
assert_equal [[6], [4, 5]], albums_by_band.map { |al| al.map(&:id) }
141+
assert_includes log, 'SELECT "albums".* FROM "albums" WHERE (created_at >= ?) AND "albums"."band_id" IN (?, ?)'
142+
143+
albums = nil
144+
log = with_active_record_log(colorize: false) do
145+
albums = d.with(GraphQL::Dataloader::ActiveRecordSource, Album).load_all([3,4,5,6])
146+
end
147+
148+
assert_equal [3,4,5,6], albums.map(&:id)
149+
assert_includes log, 'WHERE "albums"."id" IN (?, ?, ?, ?) [["id", 3], ["id", 4], ["id", 5], ["id", 6]]'
150+
end
151+
129152
if Rails::VERSION::STRING > "7.1" # not supported in <7.1
130153
it_dataloads "loads with composite primary keys and warms the cache" do |d|
131154
my_first_car = ::Album.find(2)

spec/support/active_record_setup.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
t.integer :band_id
7171
t.string :band_name
7272
t.integer :band_genre
73+
t.timestamps
7374
end
7475

7576
create_table :books do |t|

0 commit comments

Comments
 (0)