🌍 All

About us

Design

Development

Digitalization

News

Startups

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 highlightgem ‘graphql’ to your Gemfile.

For testing your queries in development, add highlightgem ‘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 highlightlike...

How to write a Software Requirements Specification (SRS) for a startup MVP?
Ruby on RailsMVPAgile

How to write a Software Requirements Specification (SRS) for a startup MVP?

Whether you are launching your first startup or you are a seasoned entrepreneur, you should always begin your work with clearly outlining the project's structure. A software requirement specification will help you communicate with the development team and make sure that they deliver what you expect, not what they assume you expect.

Michał Merchelski

Aug 27, 20185 min read

What is Ruby on Rails?
Ruby on RailsSoftware development

What is Ruby on Rails?

Ruby on Rails is an open-source web framework written in the Ruby programming language. The so-called ‘RoR’ aims to simplify the creation of web applications by generating default structures for code, the application’s database, and the web pages that will be served up to the client. Developers love it for its readability, flexibility, and continuously growing community support.

Kasia Pryczek

Jan 27, 20205 min read

Tutorial on how to install Ruby, Ruby on Rails and how to use Ruby Gems
Ruby on RailsBack-end developmentComputer programming

Tutorial on how to install Ruby, Ruby on Rails and how to use Ruby Gems

Discover a step-by-step guide on installing and utilizing Ruby on Rails for efficient web application development. Learn how to set up Ruby, manage different versions, work with RubyGems and Bundler, and create a new Ruby on Rails project. Start your journey into Ruby on Rails development with this comprehensive guide. The first step is, of course, installing Ruby itself. As the number of your projects will surely quickly increase, managing multiple variants of Ruby can become quite unpleasant. To help with that, the open source community prepared multiple version managers, with most popular ones being rbenv and rvm.

Jan Grela

Mar 20, 20206 min read

Let's talk
let's talk

Let's build

something together

highlightRethink your business, go digital.

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