class GraphQL::SmartSelect::Assosiations

Provide methods to expose foreign keys for belongs_to and has_one assosiations

Attributes

query_fields[R]
relation[R]

Public Class Methods

new(relation, query_fields) click to toggle source
# File lib/graphql/smart_select/assosiations.rb, line 12
def initialize(relation, query_fields)
  @relation = relation
  @query_fields = query_fields
end

Public Instance Methods

expose() click to toggle source
# File lib/graphql/smart_select/assosiations.rb, line 17
def expose
  assosiations_keys
end

Private Instance Methods

assosiations_keys() click to toggle source
# File lib/graphql/smart_select/assosiations.rb, line 23
def assosiations_keys
  relation.reflections.map do |assosiation_name, reflection|
    next unless required?(assosiation_name)

    if one_to_one?(reflection)
      reflection.options[:foreign_key]&.to_s || assosiation_name.foreign_key
    elsif has_many?(reflection)
      relation.primary_key
    else
      next
    end
  end.uniq
end
has_many?(reflection) click to toggle source
# File lib/graphql/smart_select/assosiations.rb, line 46
def has_many?(reflection)
  reflection.is_a?(ActiveRecord::Reflection::HasManyReflection)
end
one_to_one?(reflection) click to toggle source
# File lib/graphql/smart_select/assosiations.rb, line 41
def one_to_one?(reflection)
  reflection.is_a?(ActiveRecord::Reflection::BelongsToReflection) ||
    reflection.is_a?(ActiveRecord::Reflection::HasOneReflection)
end
required?(assosiation_name) click to toggle source
# File lib/graphql/smart_select/assosiations.rb, line 37
def required?(assosiation_name)
  query_fields.include? assosiation_name
end