Method: ActiveRecord::Relation#load_async

Defined in:
activerecord/lib/active_record/relation.rb

#load_asyncObject

Schedule the query to be performed from a background thread pool.

Post.where(published: true).load_async # => #<ActiveRecord::Relation>

When the Relation is iterated, if the background query wasn’t executed yet, it will be performed by the foreground thread.

Note that config.active_record.async_query_executor must be configured for queries to actually be executed concurrently. Otherwise it defaults to executing them in the foreground.

If the query was actually executed in the background, the Active Record logs will show it by prefixing the log line with ASYNC:

ASYNC Post Load (0.0ms) (db time 2ms)  SELECT "posts".* FROM "posts" LIMIT 100


1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
# File 'activerecord/lib/active_record/relation.rb', line 1156

def load_async
  with_connection do |c|
    return load if !c.async_enabled?

    unless loaded?
      result = exec_main_query(async: !c.current_transaction.joinable?)

      if result.is_a?(Array)
        @records = result
      else
        @future_result = result
      end
      @loaded = true
    end
  end

  self
end