Class: GraphQL::Dataloader::ActiveRecordAssociationSource

Inherits:
Source
  • Object
show all
Defined in:
lib/graphql/dataloader/active_record_association_source.rb

Constant Summary collapse

RECORD_SOURCE_CLASS =
ActiveRecordSource

Constants inherited from Source

Source::MAX_ITERATIONS

Instance Attribute Summary

Attributes inherited from Source

#dataloader, #pending, #results

Instance Method Summary collapse

Methods inherited from Source

batch_key_for, #clear_cache, #load_all, #merge, #pending?, #request, #request_all, #result_key_for, #run_pending_keys, #setup, #sync

Constructor Details

#initialize(association, scope = nil) ⇒ ActiveRecordAssociationSource

Returns a new instance of ActiveRecordAssociationSource.

[View source]

10
11
12
13
# File 'lib/graphql/dataloader/active_record_association_source.rb', line 10

def initialize(association, scope = nil)
  @association = association
  @scope = scope
end

Instance Method Details

#fetch(records) ⇒ Object

[View source]

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/graphql/dataloader/active_record_association_source.rb', line 23

def fetch(records)
  record_classes = Set.new.compare_by_identity
  associated_classes = Set.new.compare_by_identity
  records.each do |record|
    if record_classes.add?(record.class)
      reflection = record.class.reflect_on_association(@association)
      if !reflection.polymorphic? && reflection.klass
        associated_classes.add(reflection.klass)
      end
    end
  end

  available_records = []
  associated_classes.each do |assoc_class|
    already_loaded_records = dataloader.with(RECORD_SOURCE_CLASS, assoc_class).results.values
    available_records.concat(already_loaded_records)
  end

  ::ActiveRecord::Associations::Preloader.new(records: records, associations: @association, available_records: available_records, scope: @scope).call

  loaded_associated_records = records.map { |r| r.public_send(@association) }
  records_by_model = {}
  loaded_associated_records.each do |record|
    if record
      updates = records_by_model[record.class] ||= {}
      updates[record.id] = record
    end
  end

  if @scope.nil?
    # Don't cache records loaded via scope because they might have reduced `SELECT`s
    # Could check .select_values here?
    records_by_model.each do |model_class, updates|
      dataloader.with(RECORD_SOURCE_CLASS, model_class).merge(updates)
    end
  end

  loaded_associated_records
end

#load(record) ⇒ Object

[View source]

15
16
17
18
19
20
21
# File 'lib/graphql/dataloader/active_record_association_source.rb', line 15

def load(record)
  if (assoc = record.association(@association)).loaded?
    assoc.target
  else
    super
  end
end