Using D3 In Rails

I’ve been learning Rails lately, it’s amazing how the framework lets you to make a functional website with minimal thought or effort. I was cruising along until I decided to try and add a slick d3 visualization into my app, this part required a bit of poking around to get right. In the interest of helping others I present here a minimal Rails app that displays a simple d3 visualization.

This is the humble graph we will be creating.

This is the humble graph we will be creating.

We begin with a fresh Rails 4.2.0 app, initialized by rails new. From there we need to modify or create the following files to display our chart:

app/assets/javascript/graph.js       //actual d3 code goes here
app/assets/javascript/application.js //include d3.js library
app/controllers/graph_controller.rb  //this controller will serve the data for our graph
app/views/graph/index.html.erb       //this template contains the rendering endpoint
app/config/routes.rb                 //route our graph and data endpoints
app/vendor/javascripts/d3.js         //the d3 library itself

First we start with the controller. Our controller is very simple:

There are two methods here, index simply gives us our template that will hold the graph, and data gives us the json we will use to build the graph. One issue that arises is that Rails does not like just serving json, it defaults to trying to serve .erb. So we need to configure Rails to serve json from the data method, we do this in config/routes.rb like so:

Failing to change the default format for graph/data will result in an ActionController::UnknownFormat error.

Next we need some actual d3 code that will grab the data from graph/data and use it. We start with putting the d3.js library file in the canonical app/vendor/javascripts folder. However, for our app to actually use any of the libraries in vendor/javascripts, we need to include them by adding an include statement in app/vendor/javascripts/application.js:

With that out of the way we can finally write some d3:

Pretty simple stuff. We will make an AJAX request to graph/data and then render a bar chart.

Finally the last piece is our graph/index template, all we need is an svg with id graph there:

And we’re done! Rails stitches together the rest for us. Feel free to clone this as a project seed: