Class: RailsAuditLog::Graphql::Sources::RecordByIdSource

Inherits:
GraphQL::Dataloader::Source
  • Object
show all
Defined in:
lib/rails_audit_log/graphql/sources/record_by_id_source.rb

Overview

Dataloader source that batch-loads ActiveRecord records by class name and ID, returning their attributes hash.

Used internally by Types::ActorType and Types::AuditedResourceType to resolve the record field without N+1 queries.

Examples:

Manual use in a custom resolver

dataloader.with(RecordByIdSource, "User").load("42")

Instance Method Summary collapse

Constructor Details

#initialize(class_name) ⇒ RecordByIdSource

Returns a new instance of RecordByIdSource.

Parameters:

  • class_name (String)

    the ActiveRecord model class name to load from



16
17
18
# File 'lib/rails_audit_log/graphql/sources/record_by_id_source.rb', line 16

def initialize(class_name)
  @class_name = class_name
end

Instance Method Details

#fetch(ids) ⇒ Array<Hash, nil>

Batch-loads records for the given IDs.

Parameters:

  • ids (Array<String>)

    record IDs to load

Returns:

  • (Array<Hash, nil>)

    attributes hash for each ID, or nil when the record does not exist or the class cannot be constantized



25
26
27
28
29
30
31
# File 'lib/rails_audit_log/graphql/sources/record_by_id_source.rb', line 25

def fetch(ids)
  klass = @class_name.safe_constantize
  return ids.map { nil } unless klass

  records = klass.where(id: ids).index_by { |r| r.id.to_s }
  ids.map { |id| records[id]&.attributes }
end