Published on
2 min read

GraphQL Server - Nested Query Implementation Example in Ruby on Rails

Authors

One of the main advantages of GraphQL is that we can create queries with different combinations of datasets, avoiding multiple requests to fetch required data. In this post, I discuss how to create nested datasets.

In the previous post, I introduced the Article model. Now, let's fetch comments and the users who wrote them.

1. Define CommentType

# app/graphql/types/comment_type.rb
CommentType = GraphQL::ObjectType.define do
  name "Comment"
  field :id, types.Int
  field :comment, types.String
  field :user, UserType
end

2. Define UserType

# app/graphql/types/user_type.rb
UserType = GraphQL::ObjectType.define do
  name "User"
  field :id, types.Int
  field :name, types.String
  field :email, types.String
end

3. Update ArticleType

Expose the comments association:

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

Since the Article model has many comments, we use types[CommentType] to specify an array of objects.

Nested Query Example

Fetch an article, its comments, and the commented users:

query {
  article(id: 1) {
    title
    comments {
      comment
      user {
        id
        name
      }
    }
  }
}

Response:

{
  "data": {
    "article": {
      "title": "A GraphQL Server",
      "comments": [
        {
          "comment": "Good article",
          "user": {
            "id": 1,
            "name": "Shaiju E"
          }
        }
      ]
    }
  }
}

You can see the sample code here.

TwitterLinkedInHacker News