Class: GraphQL::Sources::ActiveStorageHasOneAttached

Inherits:
ActiveStorageBase
  • Object
show all
Defined in:
lib/graphql/sources/active_storage_has_one_attached.rb

Overview

A class for loading ‘has_one_attached` style associations.

class User
  has_one_attached :photo
end

class UserType < GraphQL::Schema::Object
  field :avatar, AttachedType, null: false

  def avatar
    dataloader
      .with(GraphQL::Sources::ActiveStorageHasOneAttached, :avatar)
      .load(object)
  end
end

The resulting SQL query is:

SELECT "active_storage_attachments".*
FROM "active_storage_attachments"
WHERE "active_storage_attachments"."name" = 'avatar'
  AND "active_storage_attachments"."record_type" = 'User'
  AND "active_storage_attachments"."record_id" IN (...)

Instance Method Summary collapse

Methods inherited from ActiveStorageBase

#initialize

Constructor Details

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

Instance Method Details

#fetch(records) ⇒ Array

Returns indexed attachments mirroring the keys.

Parameters:

  • records (Array<ActiveRecord::Base>)

    an array of records

Returns:

  • (Array)

    indexed attachments mirroring the keys



31
32
33
34
35
36
37
# File 'lib/graphql/sources/active_storage_has_one_attached.rb', line 31

def fetch(records)
  attachments = attachments(records: records).load_async
  dataloader.yield

  map = attachments.index_by { |attachment| [attachment.record_type, attachment.record_id] }
  records.map { |record| map[[record.class.name, record.id]] }
end