Unions allow you to group different object types into a single type. They’re perfect for fields that can return one of several possible object types, like polymorphic associations or search results.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/virtualshield/rails-graphql/llms.txt
Use this file to discover all available pages before exploring further.
Basic Union Definition
Define unions in files or inline within your schema:Adding Members
Use theappend method to add object types to the union:
Validation Rules
Unions enforce strict validation:- Minimum members: Must contain at least one member
- Same base class: All members must share the same base class
- Object types only: Members must be
GraphQL::Objecttypes
Type Resolution
Unions require type resolution to determine which member type represents a given value:Default Resolution
The defaulttype_for method checks each member type:
Custom Resolution
Override for specific logic, like polymorphic associations:Key Differences from Interfaces
Unions and interfaces both enable polymorphism but serve different purposes:Unions
- No shared fields
- Group unrelated types
- Pure composition
- Perfect for polymorphic belongs_to
Interfaces
- Define shared fields
- Objects inherit fields
- Shared resolution logic
- Perfect for STI models
Unions cannot have fields. To access any data, you must use spreads to query type-specific fields.
Usage in Queries
Unions require spreads to access fields since they don’t define any themselves:Query with Spreads
The
__typename field is the only field you can query directly on a union. Use spreads for everything else.Common Patterns
Polymorphic Associations
Polymorphic Belongs To
Search Results
Multiple Content Types
Activity Feeds
Different Event Types
Error Handling
Success or Error
Descriptions
Document unions for API clarity:Inspecting Unions
Unions provide helpful inspection output:Best Practices
When to use unions:
- Polymorphic belongs_to associations
- Search results across multiple types
- Activity feeds with different event types
- Result types (success/error patterns)
- Any field that returns “one of several types”
Member Access
Access union members programmatically:Related Documentation
- Interfaces - Alternative for types with shared fields
- Objects - Define union members
- Spreads - Query type-specific fields
- Polymorphic Associations - Rails pattern