Class: GraphQL::Sources::ActiveRecordCount
- Inherits:
-
ActiveRecordBase
- Object
- Dataloader::Source
- ActiveRecordBase
- GraphQL::Sources::ActiveRecordCount
- 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
-
#fetch(keys) ⇒ Array
Grouped counts for the keys.
Methods inherited from ActiveRecordBase
Constructor Details
This class inherits a constructor from GraphQL::Sources::ActiveRecordBase
Instance Method Details
#fetch(keys) ⇒ Array
Returns 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 |