Skip to content

Commit 9ecc9d2

Browse files
committed
Add AR::Base#load_async(*associations) as a nicer API
1 parent f30028d commit 9ecc9d2

File tree

5 files changed

+10
-5
lines changed

5 files changed

+10
-5
lines changed

activerecord/lib/active_record/associations.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,11 @@ def association(name) # :nodoc:
324324
association
325325
end
326326

327+
def load_async(*associations) # TODO: doc
328+
associations.map { |name| association(name) }.each(:async_load_target)
329+
self
330+
end
331+
327332
def association_cached?(name) # :nodoc:
328333
@association_cache.key?(name)
329334
end

activerecord/lib/active_record/associations/association.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def async_load_target
191191
@target = find_target(async: true) if (@stale_state && stale_target?) || find_target?
192192

193193
loaded! unless loaded?
194-
@target
194+
nil
195195
end
196196

197197
# We can't dump @reflection and @through_reflection since it contains the scope proc
@@ -241,7 +241,7 @@ def find_target(async: false)
241241
if async
242242
return scope.load_async.then(&:to_a)
243243
else
244-
return scope.to_a
244+
return scope.to_a
245245
end
246246
end
247247

activerecord/test/cases/associations/belongs_to_associations_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1853,7 +1853,7 @@ def test_async_load_belongs_to
18531853
client = Client.find(3)
18541854
first_firm = companies(:first_firm)
18551855

1856-
promise = client.association(:firm).async_load_target
1856+
promise = client.load_async(:firm)
18571857
wait_for_async_query
18581858

18591859
events = []

activerecord/test/cases/associations/has_many_associations_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3248,7 +3248,7 @@ class AsyncHasOneAssociationsTest < ActiveRecord::TestCase
32483248
def test_async_load_has_many
32493249
firm = companies(:first_firm)
32503250

3251-
promise = firm.association(:clients).async_load_target
3251+
promise = firm.load_async(:clients)
32523252
wait_for_async_query
32533253

32543254
events = []

activerecord/test/cases/associations/has_one_associations_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -953,7 +953,7 @@ def test_async_load_has_one
953953
firm = companies(:first_firm)
954954
first_account = Account.find(1)
955955

956-
promise = firm.association(:account).async_load_target
956+
promise = firm.load_async(:account)
957957
wait_for_async_query
958958

959959
events = []

0 commit comments

Comments
 (0)