Polymorphic associations on Ruby on Rails Guide
Problem statement
Polymorphic associations are most often used in a Rails application. With GraphQL ruby one of the problems we come across is to How to resolve polymorphic types in GraphQL-ruby?
.
The solution is to use Union types. To understand more on how to resolve polymorphic types lets take the following example of Polymorphic association from Ruby on Rails Guide.
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
In the above example, imageable
Polymorphic association for PictureType
can be either an Employee
or Product
as imageable. Employee
and Product
may have different properties and to resolve the different properties, the GraphQL type should know what type of fields the object would resolve. This is where Union Types come into the picture.
Definition from GraphQL-ruby guides
What is Union Types?
A union type is a set of object types which may appear in the same spot.
// apps/graphql/types/picture_type.rb
class Types::PictureType < Types::BaseObject
description "Properties of Picture"
field :id, ID, null: false
field :imageable, Types::ImageType, null: false
end
Now, add a ImageType
which may either resolve ProductType
or EmployeeType
.
class Types::ImageType < Types::BaseUnion
description "Properties of Image"
possible_types Types::EmployeeType,
Types::ProductType,
def self.resolve_type(object, context)
if object.is_a?(Employee)
Types::EmployeeType
elsif object.is_a?(Product)
Types::ProductType
end
end
end
The GraphQL query would now be written as follows.
pictures {
id
... on Employee {
first_name
last_name
address
}
... on Product {
name
price
}
}
Happy Coding!!