Skip to content

Commit

Permalink
Add AR::Base#load_async(*associations) as a nicer API
Browse files Browse the repository at this point in the history
  • Loading branch information
byroot committed Apr 15, 2024
1 parent f30028d commit 9ecc9d2
Show file tree
Hide file tree
Showing 5 changed files with 10 additions and 5 deletions.
5 changes: 5 additions & 0 deletions activerecord/lib/active_record/associations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,11 @@ def association(name) # :nodoc:
association
end

def load_async(*associations) # TODO: doc
associations.map { |name| association(name) }.each(:async_load_target)
self
end

def association_cached?(name) # :nodoc:
@association_cache.key?(name)
end
Expand Down
4 changes: 2 additions & 2 deletions activerecord/lib/active_record/associations/association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def async_load_target
@target = find_target(async: true) if (@stale_state && stale_target?) || find_target?

loaded! unless loaded?
@target
nil
end

# We can't dump @reflection and @through_reflection since it contains the scope proc
Expand Down Expand Up @@ -241,7 +241,7 @@ def find_target(async: false)
if async
return scope.load_async.then(&:to_a)
else
return scope.to_a
return scope.to_a
end
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1853,7 +1853,7 @@ def test_async_load_belongs_to
client = Client.find(3)
first_firm = companies(:first_firm)

promise = client.association(:firm).async_load_target
promise = client.load_async(:firm)
wait_for_async_query

events = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3248,7 +3248,7 @@ class AsyncHasOneAssociationsTest < ActiveRecord::TestCase
def test_async_load_has_many
firm = companies(:first_firm)

promise = firm.association(:clients).async_load_target
promise = firm.load_async(:clients)
wait_for_async_query

events = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,7 @@ def test_async_load_has_one
firm = companies(:first_firm)
first_account = Account.find(1)

promise = firm.association(:account).async_load_target
promise = firm.load_async(:account)
wait_for_async_query

events = []
Expand Down

0 comments on commit 9ecc9d2

Please sign in to comment.