How to set up a project with Ruby on Rails, PostgreSQL and GraphQL
Setting up a project with Ruby on Rails, PostgreSQL and GraphQL is actually pretty straightforward. 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.