Class: GraphQL::Sources::ActiveRecordObject

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

Overview

A class for loading ‘has_one` style associations.

class User
  has_one :profile
end

class Profile
  belongs_to :user
end

class UserType < GraphQL::Schema::Object
  field :profile, [ProfileType], null: false

  def profile
    dataloader
      .with(GraphQL::Sources::ActiveRecordCollection, ::Profile, key: :user_id)
      .load(object.id)
  end
end

The resulting SQL query is:

SELECT "profiles".*
FROM "profiles"
WHERE "profiles"."user_id" IN (1, 2, 3, ...)
ORDER BY "profiles"."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 indexed records mirroring the keys.

Parameters:

  • keys (Array)

    an array of keys

Returns:

  • (Array)

    indexed records mirroring the keys



34
35
36
37
38
39
40
# File 'lib/graphql/sources/active_record_object.rb', line 34

def fetch(keys)
  models = models(keys: keys).order(:id).load_async
  dataloader.yield

  map = models.index_by { |model| model[@key] }
  keys.map { |key| map[key] }
end