Class: GraphQL::Sources::ActiveRecordCount

Inherits:
ActiveRecordBase
  • Object
show all
Defined in:
lib/graphql/sources/active_record_count.rb

Overview

A class for loading a count of records.

class Post
  has_many :likes
end

class Like
  belongs_to :post
end

class PostType < GraphQL::Schema::Object
  field :likes, Integer, null: false

  def likes
    dataloader
      .with(GraphQL::Sources::ActiveRecordCount, ::Like, key: :post_id)
      .load(object.id)
  end
end

The resulting SQL query is:

SELECT "likes"."post_id", COUNT(*)
FROM "likes"
WHERE "likes"."post_id" IN (1, 2, 3, ...)
GROUP BY "likes"."post_id"

Instance Method Summary collapse

Methods inherited from ActiveRecordBase

#initialize

Constructor Details

This class inherits a constructor from GraphQL::Sources::ActiveRecordBase

Instance Method Details

#fetch(keys) ⇒ Array

Returns grouped counts for the keys.

Parameters:

  • keys (Array)

    an array of keys

Returns:

  • (Array)

    grouped counts for the keys



34
35
36
37
# File 'lib/graphql/sources/active_record_count.rb', line 34

def fetch(keys)
  map = models(keys: keys).group(@key).count
  keys.map { |key| map[key] || 0 }
end