Method: Simple::SQL::Result::AssociationLoader#preload

Defined in:
lib/simple/sql/result/association_loader.rb

#preload(connection, records, association, host_table:, schema:, as:, order_by:, limit:) ⇒ Object

Preloads a association into the records array.

Parameters:

  • records: an Array of hashes.

  • association: the name of the association

  • host_table: the name of the table a records has been loaded from.

  • schema: the schema name in the database.

  • as: the name to sue for the association. Defaults to association



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/simple/sql/result/association_loader.rb', line 152

def preload(connection, records, association, host_table:, schema:, as:, order_by:, limit:)
  return records if records.empty?

  expect! records.first => Hash

  as = association if as.nil?
  fq_host_table = "#{schema}.#{host_table}"

  associated_table = find_associated_table(connection, association, schema: schema)
  relation         = find_matching_relation(connection, fq_host_table, associated_table)

  if fq_host_table == relation.belonging_table
    if order_by || limit
      raise ArgumentError, "#{association.inspect} is a singular association, w/o support for order_by: and limit:"
    end

    preload_belongs_to connection, records, relation, as: as
  else
    preload_has_one_or_many connection, records, relation, as: as, order_by: order_by, limit: limit
  end
end