Class: GraphQL::Dataloader::ActiveRecordAssociationSource
- Inherits:
-
Source
- Object
- Source
- GraphQL::Dataloader::ActiveRecordAssociationSource
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
Class Method Summary
collapse
Instance Method Summary
collapse
Methods inherited from Source
#clear_cache, #load_all, #merge, #normalize_fetch_key, #pending?, #request, #request_all, #result_key_for, #run_pending_keys, #setup, #sync
Constructor Details
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
|
Class Method Details
.batch_key_for(association, scope = nil) ⇒ Object
15
16
17
18
19
20
21
|
# File 'lib/graphql/dataloader/active_record_association_source.rb', line 15
def self.batch_key_for(association, scope = nil)
if scope
[association, scope.to_sql]
else
[association]
end
end
|
Instance Method Details
#fetch(records) ⇒ Object
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
# File 'lib/graphql/dataloader/active_record_association_source.rb', line 31
def fetch(records)
record_classes = Set.new.compare_by_identity
associated_classes = Set.new.compare_by_identity
scoped_fetch = !@scope.nil?
records.each do |record|
if scoped_fetch
assoc = record.association(@association)
assoc.reset
end
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|
assoc = r.association(@association)
lar = assoc.target
if scoped_fetch
assoc.reset
end
lar
}
if !scoped_fetch
records_by_model = {}
loaded_associated_records.flatten.each do |record|
if record
updates = records_by_model[record.class] ||= {}
updates[record.id] = record
end
end
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
23
24
25
26
27
28
29
|
# File 'lib/graphql/dataloader/active_record_association_source.rb', line 23
def load(record)
if (assoc = record.association(@association)).loaded?
assoc.target
else
super
end
end
|