Class: Ibrain::Loaders::AssociationCountLoader

Inherits:
GraphQL::Batch::Loader
  • Object
show all
Defined in:
app/graphql/ibrain/loaders/association_count_loader.rb

Instance Method Summary collapse

Constructor Details

#initialize(model, association_name) ⇒ AssociationCountLoader

Returns a new instance of AssociationCountLoader.



6
7
8
9
10
# File 'app/graphql/ibrain/loaders/association_count_loader.rb', line 6

def initialize(model, association_name)
  super()
  @model = model
  @association_name = association_name
end

Instance Method Details

#perform(records) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'app/graphql/ibrain/loaders/association_count_loader.rb', line 12

def perform(records)
  reflection = @model.reflect_on_association(@association_name)
  reflection.check_preloadable!

  klass = reflection.klass
  field = reflection.join_primary_key
  counts = klass.unscoped.where(field => records).group(field).count

  records.each do |record|
    record_key = record[reflection.active_record_primary_key]
    fulfill(record, counts[record_key] || 0)
  end
end