belongs_to_resolver.rb 916 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Gql::Resolvers::BelongsToResolver < GraphQL::Schema::Resolver
  3. include Gql::Types::Concerns::HasPunditAuthorization
  4. description "resolver for Rails' belongs_to relationship"
  5. def resolve
  6. Gql::RecordLoader
  7. .for(target_object_klass)
  8. .load(target_object_id)
  9. end
  10. private
  11. def target_object_klass
  12. if field.through_key.present?
  13. return ObjectLookup
  14. .by_id(object.send(field.through_key))
  15. .constantize
  16. end
  17. rails_definition
  18. .klass
  19. end
  20. def target_object_id
  21. if field.through_key.present?
  22. return object.public_send(field.foreign_key)
  23. end
  24. db_column = field.foreign_key || :"#{rails_definition.plural_name.singularize}_id"
  25. object.public_send(db_column)
  26. end
  27. def rails_definition
  28. object.class.reflections[field.original_name.to_s]
  29. end
  30. end