Contact us

🌍 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, 20213 min read

Ruby on RailsGraphQLBack-end development

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 .

 
How to set up a project with Ruby on Rails, PostgreSQL and GraphQL

Published on September 24, 2021

Share


Anna Dydio Junior Ruby Developer

Don't miss a beat - subscribe to our newsletter
I agree to receive marketing communication from Startup House. Click for the details

You may also like...

Backend Development Services: The Essentials You Need to Know
Back-end developmentDigital transformation

Backend Development Services: The Essentials You Need to Know

Learn the essentials of backend development in this practical guide. Explore core components, best practices, and emerging trends to build robust, scalable web applications.

Marek Pałys

Mar 05, 20245 min read

Travel Backend Development
Back-end developmentInnovations in travel

Travel Backend Development

Travel backend development is crucial for creating seamless travel experiences by managing bookings, handling transactions, and integrating various APIs. This guide explores the essential technologies, challenges, and future trends in travel backend development, ensuring robust and efficient systems for the travel industry.

Marek Majdak

Apr 11, 202411 min read

Navigating Tech Choices: Ruby or Java for Enhanced Productivity in Small Businesses
Ruby on Rails

Navigating Tech Choices: Ruby or Java for Enhanced Productivity in Small Businesses

Choosing between Ruby and Java significantly influences small business productivity, with Ruby offering rapid development and Java known for robust performance. This guide dives into the performance differences, helping business owners make informed tech decisions to enhance operations and competitiveness. Whether it's Ruby's developer-friendly approach or the ruby performance vs Java's scalability and reliability, the right programming language can drive your business forward in a competitive market.

Marek Majdak

Mar 22, 20245 min read

Let's talk
let's talk

Let's build

something together

Startup Development House sp. z o.o.

Aleje Jerozolimskie 81

Warsaw, 02-001

VAT-ID: PL5213739631

KRS: 0000624654

REGON: 364787848

Contact us

Follow us

logologologologo

Copyright © 2024 Startup Development House sp. z o.o.

EU ProjectsPrivacy policy