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 User
  has_many :purchases
end

class Product
  has_many :purchases
end

class Purchase
  belongs_to :product
  belongs_to :user
end

class ProductType < GraphQL::Schema::Object
  field :purchased, Boolean, null: false

  def purchased
    dataloader
      .with(GraphQL::Sources::ActiveRecordCount, ::Purchase.where(user: context.user), key: :product_id)
      .load(object.id)
  end
end

The resulting SQL query is:

SELECT "purchases"."post_id", COUNT(*)
FROM "purchases"
WHERE "purchases"."user_id" = ... AND "purchases"."product_id" IN (1, 2, 3, ...)
GROUP BY "purchases"."post_id"

Instance Method Summary collapse

Methods inherited from ActiveRecordBase

batch_key_for, #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



39
40
41
42
# File 'lib/graphql/sources/active_record_count.rb', line 39

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