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 authored and andrewn617 committed Sep 5, 2024
1 parent a3a2e19 commit f29d019
Show file tree
Hide file tree
Showing 6 changed files with 15 additions and 9 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 @@ -62,6 +62,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 @@ -247,7 +247,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
9 changes: 5 additions & 4 deletions activerecord/lib/active_record/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -432,10 +432,11 @@ def cached_find_by(keys, values)
where(wheres).limit(1)
}

begin
statement.execute(values.flatten, lease_connection, allow_retry: true).then(&:first)
rescue TypeError
raise ActiveRecord::StatementInvalid
begin
statement.execute(values.flatten, lease_connection, allow_retry: true).then(&:first)
rescue TypeError
raise ActiveRecord::StatementInvalid
end
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1851,7 +1851,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 @@ -3263,7 +3263,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 @@ -955,7 +955,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 f29d019

Please sign in to comment.