GraphQL. The Rails way

Povilas Jurčys
2 min readApr 28, 2019

So you have or you are considering to have GraphQL in your Ruby on Rails project. Let me guess — you are using graphql-ruby gem. This gem is nice, but it does not have very good integration with Ruby on Rails and requires to write different style of code. There is an alternative which I would like to introduce.

If you want to keep your code nice and clean, then I would recommend using graphql_rails instead. graphql_rails offers object oriented design by encapsulating queries and allows easy testing. It introduces routers, controllers and models — basically everything that can be found in Ruby on Rails.

It allows sharing same behavior between Rails and on GraphQL controllers via modules. This is especially handy if you want different GraphQL requests to be logged by monitoring tool such as Airbrake, Sentry, Kibana or if you want to have same logic for authenticating users on GraphQL and Rails side (before_action :authenticate_user!)

Using gem in Ruby on Rails

Here is how you define model in graphql_rails:

GraphQL requires type for each input and output, thus you need to declare what type each of your attribute has.

Now here is the way to add controller in graphql_rails:

The main difference between Rails and GraphQL controllers is that you must add settings for each controller action. This is required because, again, GraphQL has types and you need to specify type for each input and output value.

Eager for more?

I covered only the essence of graphql_rails gem. It has a lot of handy tools which were not covered here. For more details see It also has user friendly documentation with even more examples:

Happy coding!