Rails Kitchen

It's a place to write on stuff I learned recently.

Preload Has_many Associations in Graphql-ruby Using Graphql-preload

| Comments

In the previous post about solving N+1 query in graphQL using graphql-batch, we discussed batching queries using the graphql-batch gem. This works great for belongs_to relationships, but it is not useful for preloading has_many associations. For example, if you wanted the comments for each article, it would again produce N+1 queries. Luckily I found a gem graphql-preload that solves this problem. The graphql-preload gem is created based on a gist by @theorygeek. This gem depends on the graphql-batch gem. so we need to keep graphql-batch settings in the schema for graphql-preload work. detailed explanation about graphql batch is given here.

Installation

Add this line to your application’s Gemfile:
Gemfile
1
gem 'graphql-preload'
Add enable_preloading to the schema file to be able to use this functionality.
app/graphql/graphql_ruby_sample_schema.rb
1
2
3
4
5
6
7
GraphqlRubySampleSchema = GraphQL::Schema.define do
  query QueryType
  mutation MutationType

  use GraphQL::Batch
  enable_preloading
end
Now, for the comments field, for example, we could write it like this:
app/graphql/types/article_type.rb
1
2
3
4
5
6
7
ArticleType = GraphQL::ObjectType.define do
  name "Article"

  field :comments, types[CommentType] do
    preload :comments
  end
end
We can now throw a query like this at our API without the server with N+1 query problem for has_many association also.
1
2
3
4
5
6
7
8
9
10
11
12
13
query {
  articles{
    id
    title
    body
    comments{
      comment
      user{
        name
      }
    }
  }
}
Before preload After preload

Comments