Class: GraphQL::ActiveRecordBatcher::AssociationLoader

Inherits:
Batch::Loader
  • Object
show all
Defined in:
lib/graphql/active_record_batcher/association_loader.rb

Instance Method Summary collapse

Constructor Details

#initialize(model, association) ⇒ AssociationLoader

Returns a new instance of AssociationLoader.



7
8
9
10
# File 'lib/graphql/active_record_batcher/association_loader.rb', line 7

def initialize(model, association)
  @model = model
  @association = association
end

Instance Method Details

#cache_key(record) ⇒ Object

We want to load the associations on all records, even if they have the same id



19
20
21
# File 'lib/graphql/active_record_batcher/association_loader.rb', line 19

def cache_key(record)
  record.object_id
end

#load(record) ⇒ Object

Raises:

  • (TypeError)


12
13
14
15
16
# File 'lib/graphql/active_record_batcher/association_loader.rb', line 12

def load(record)
  raise TypeError, "#{@model} loader can't load association for #{record.class}" unless record.is_a?(@model)
  return Promise.resolve(read_association(record)) if association_loaded?(record)
  super
end

#perform(records) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/graphql/active_record_batcher/association_loader.rb', line 23

def perform(records)
  ::ActiveRecord::Associations::Preloader.new.preload(records, association)

  records.each do |record|
    association_result = record.public_send(association)
    fulfill(record, association_result)
  end
end