🌍 All
About us
Digitalization
News
Startups
Development
Design
How to set up a project with Ruby on Rails, PostgreSQL and GraphQL
Anna Dydio
Sep 24, 2021・3 min read
Table of Content
Setting Up GraphQL for Rails
Afterword
Setting up a project with Ruby on Rails, PostgreSQL and GraphQL is actually pretty straightforward.
But first, some prerequisites. For this tutorial (tested on versions 2.7.3, 6.1.4.1 and 11.0 respectively), you must have all three, Ruby on Rails, PostgreSQL and GraphQL installed on your development machine.
Some general knowledge of Ruby and Rails is also recommended.
Before we begin, however, you might be wondering why anyone would want to replace the perfectly fine experience provided by the traditional REST API with one offered by GraphQL. Well, one obvious reason is that GraphQL deals quite elegantly with resources over- and under-fetching. With GraphQL you are given the exact information you request - nothing more, nothing less. Moreover, it is almost self-documenting, making that one less item on your list of things to worry about. And there are other pros to GraphQL, such as it being both strongly typed and language and database independent. But in the meantime, I'll leave those for you to explore on your own.
So, without further ado, let’s set up our first GraphQL API on Ruby on Rails.
Setting Up GraphQL for Rails
Step 1 - PostgreSQL database
Let’s create a Ruby on Rails API app with PostgreSQL as the database. We’ll be making a very simple bookshelf API.
rails new bookshelf_app -d=postgresql -T —api
Step 2 - GraphQL to Gemfile
Let’s add GraphQL to our project. To do so, add gem ‘graphql’ to your Gemfile.
For testing your queries in development, add gem ‘graphiql-rails’ under the development category.
Now, let’s install our gems.
bundle install
rails g graphql:install
Make sure that your config/routes.rb includes the following:
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: 'graphiql', graphql_path:
‘graphql#execute’
end
post ‘/graphql', to: ‘graphql#execute’
Step 3 - Create database
Time to create the database and start the server.
rails db:create db:migrate
rails s
Now go to localhost:3000/graphiql (or a different port if specified) in your browser. If you can see the graphiql interface, you can skip step 4.
Step 4 - Loading...
In case you keep seeing the Loading… page, go to config/application.rb and uncomment the line requiring “sprockets/railtie”. Then, create an empty app/assets/config/manifest.js file.
Restart your server. You should be able to access the graphiql interface by now.
Step 5 - Author, Books
Next, we'll create some resources by generating author and book models. Authors can have many books and books belong to the authors.
rails g model Author name
rails g model Book title:text author:references genre:text description
rails db:migrate
Open your author model file, add has_many :books, and save so that our associations are on point.
Great - we're now ready to work with GraphQL!
Step 6 - Author/ Book Types
Let’s create author and book types.
rails generate graphql:object author
rails generate graphql:object book
Open the author_type.rb file and add field :books, [Types::BookType], null: true under other fields so that when querying for authors we can also ask for the information on their books. You can think of the types as the schemas for specific resources.
Step 7 - Mutations
Now that our types are ready, we can make our first mutation. Mutations are used to modify the resources in the database.
Let’s start with the mutation to create authors. Create a file create_author.rb under app/graphql/mutations and update it as follows:
module Mutations
class CreateAuthor < BaseMutation
argument :name, String, required: true
type Types::AuthorType
def resolve(name:)
Author.create!(name: name)
end
end
end
Similarly, let’s add mutation for creating books. Create a file create_book.rb:
module Mutations
class CreateBook < BaseMutation
argument :title, String, required: false
argument :genre, String, required: false
argument :description, String, required: false
argument :author_id, ID, required: true
type Types::BookType
def resolve(**attributes)
Book.create!(attributes)
end
end
end
You can create similar mutations to update and destroy resources.
When you’re ready, add the following to your mutation_type.rb file:
field :create_author, mutation: Mutations::CreateAuthor
field :create_book, mutation: Mutations::CreateBook
To test our mutations, let’s try to create our first author. Go to our GraphiQL interface, write the following and execute the query.
mutation {
createAuthor(input: {
name: "Jane Doe"
}) {
id
name
}
}
In return you should receive a response resembling this one:
{
"data": {
"createAuthor": {
"id": "1",
"name": "Jane Doe"
}
}
Now, create your first book in a similar manner.
Step 8 - First Queries
Last but not least, let’s create our first queries. To be able to do so, update your query_type.rb file with the following. All fields created here will be available to us through the API.
field :authors, [AuthorType], null: false
field :books, [BookType], null: false
field :author, AuthorType, null: false do
argument :id, ID, required: true
end
field :book, BookType, null: false do
argument :id, ID, required: true
end
def authors
Author.all
end
def books
Book.all
end
def author(id:)
Author.find(id)
end
def book(id:)
Book.find(id)
end
Let’s run this query in the GraphiQL:
query {
author(id: 1) {
id
name
books {
id
title
}
}
}
If you added some books to the database, the response should return something similar to:
{
"data": {
"author": {
"id": "1",
"name": "Jane Doe",
"books": [
{
"id": "1",
"title": "Book 1"
},
{
"id": "2",
"title": "Book 2"
},
{
"id": "3",
"title": "Book 3"
}
]
}
}
}
Afterword
So, there you have it. And congratulations - you’ve just created your first Rails GraphQL API! If you’re looking for a means as authorization, you can always check the gem action_policy-graphql, and more tips on GraphQL in Ruby on Rails can be found at: https://www.howtographql.com/graphql-ruby/0-introduction.
Good luck!
Finally, if you'd like to find out more about the other development languages and technologies expertly employed at SDH, feel free to contact us at hello@start-up.house.
You may also like...
A Beginner's Guide to Building E-commerce Sites with Ruby on Rails
Ruby on Rails simplifies the process of building an e-commerce site, making it accessible even for beginners. This guide provides step-by-step instructions on setting up your development environment, managing products, integrating payment gateways, and enhancing user experience. Whether you're new to web development or looking to refine your skills, this guide will help you create a successful online store with Ruby on Rails.
Marek Pałys
Aug 13, 2024・5 min read
Mobile Backend as a Service
Mobile Backend as a Service (MBaaS) streamlines mobile app development by offering cloud-based backend functionalities such as data storage, user authentication, and push notifications. This allows developers to focus on front-end features while the service provider handles the complexities of backend management. Explore how MBaaS enhances app performance, simplifies development, and reduces costs, making it an essential tool for modern mobile apps.
Marek Majdak
Aug 09, 2024・5 min read
What is Backend as a Service (BaaS)?
Backend as a Service (BaaS) streamlines application development by handling backend functions such as database management, user authentication, and hosting. This allows developers to focus on front-end design and user experience, making it a popular choice for startups and small teams. Discover how BaaS can enhance your development process by reducing complexity and accelerating deployment.
Marek Majdak
Aug 02, 2024・5 min read
Let's build
something together