3

I've been searching for examples on how to translate a traditional ActiveRecod .includes for associated models, while using graphQL-ruby, and haven't found any. As a use case, let's say we have the following models:

User
has_many :books

Book
belongs_to :user
has_many :chapters

Chapter
belongs_to :book
has_many :pages

Page
belongs_to :chapter

How could we implement the following:

User.includes(books: {chapters: :pages})

The actual nested GraphQL query is relatively simple; however, it seems to be running at N+1.

Any help would be greatly appreciated.

frostini
  • 175
  • 10
  • It looks like the new Lookahead feature in v1.9 could help with this. https://graphql-ruby.org/queries/lookahead.html – mpoisot May 08 '19 at 21:52

2 Answers2

0

We wrote a small gem for graphql-ruby that generates includes by walking a GraphQL Query.

https://github.com/thesquarefoot/graphql_includable

For your example you would call User.includes_from_graphql(ctx) in the User field resolver.

Josh Vickery
  • 862
  • 7
  • 10
  • Note that this no longer works for the class based API for graphql. ctx.irep_node no longer gets passed through either, so a new solution is needed. – user1581404 Dec 04 '18 at 17:30
0

You should use graphql-preload gem to preload associations in Graphql

https://github.com/ConsultingMD/graphql-preload

Krupa Suthar
  • 670
  • 3
  • 14