GraphQL is a query language and server-side runtime for API that prioritize and give the data exactly requested. GraphQL is designed to make APIs fast, flexible, and developer-friendly.
GraphQL is language-independent, so in ruby, we can implement using the graphql gem. This gives us a specific file structure and command-line tools to easily add GraphQL functionality to our Rails API.
In this tutorial, I will explain how to integrate GraphQL with Ruby On Rails Application.
we can create new rails application to firing the following command on terminal,
$ rails new graphql-rails --api
Change the directory to the newly created rails application and create the Author and Article model.
$ cd graphql-rails
$ rails g model author name:string bio:string
$ rails g model article title:string description:text author:references
Now we can add the association and validation to the models
class Author < ApplicationRecord
has_many :articles
validates :name, presence: true
end
class Article < ApplicationRecord
belongs_to :author
validates :title, :description, presence: true
end
Using $ rake db:create we can create the database and $ rake db:migrate will create the table inside the database. Once migration is completed we can add a few data to our database. Add the following object into db/seeds.rb file
author1 = Author.create(name: ‘Arjunan’, bio: ‘Ruby developer’)
author2 = Author.create(name: ‘David’, bio: ‘Angular developer’)
Article.create(
title: ‘Basics of Ruby Programming’,
description: ‘This article is related to ruby programming’,
author: author1
)
Article.create(
title: ‘How to create Angular application’,
description: ‘This article is related to Angular App’,
author: author2
)
Running the $ rake db:seed on the rails app root directory to add the data to the database.
#ruby on rails #graphql #ror #apis #angular app