One of the main advantages of GraphQL is, we can create queries with a different combination of datasets which will avoid multiple requests to fetch required data, thereby eliminating overheads. In this post, I am discussing how we can create nested datasets in GraphQL.
In the previous post, I mentioned about Article model and query to fetch an article. Here I’m going to fetch comments under the article. Assuming we have comments and user model with corresponding associations.
Here comments are an array of objects so we need to specify CommentType using types keyword. We can see in comment_type.rb we are not specifying types for UserType, as it is returning a single object. Since we defined association in, This will fetch all comments of the article by executing article.comments.
Put below code in application.rb to autoload graphql and types folder like so: