Published on
1 min read

preload has_many associations in graphql-ruby using graphql-preload

Authors

While graphql-batch is great for belongs_to relationships, it doesn't directly handle preloading has_many associations. To solve this, I found the graphql-preload gem, which simplifies batching for collection associations.

Installation

Add it to your Gemfile:

gem 'graphql-preload'

Enable it in your schema (it requires graphql-batch to be configured first):

# app/graphql/graphql_ruby_sample_schema.rb
GraphqlRubySampleSchema = GraphQL::Schema.define do
  use GraphQL::Batch
  enable_preloading
end

Usage

Use the preload helper within your field definitions:

# app/graphql/types/article_type.rb
ArticleType = GraphQL::ObjectType.define do
  name "Article"
  field :comments, types[CommentType] do
    preload :comments
  end
end

Now, queries like the one below will execute without N+1 problems for the comments association:

query {
  articles {
    id
    title
    comments {
      comment
      user {
        name
      }
    }
  }
}

Results

Before
After
TwitterLinkedInHacker News