Home > Articles

  • Print
  • + Share This
This chapter is from the book

Create the Views

We can turn our attention to creating the chord diagram now that we have our data in place. We need a controller, view, and routes to support the view and asynchronous data call.

Departures Controller and Routes

We need two routes and actions for the view and the AJAX data callback. Just as with the other apps and charts before, the index action does not need to do anything. The real work happens when the JavaScript function calls back to the server and asks for the data. Let’s start by creating a controller (rails g controller departures --skip-helper). Put these actions in the DeparturesController.

  def index; end

  def departure_matrix
    airports, matrix = Departure.departure_matrix
    render :json => {
      :airports => airports,
      :matrix   => matrix

In order to make the controller actions do anything, we need to define some routes. Here is the cleaned up routes file:

Rails.application.routes.draw do
  root 'departures#index'
  get 'departures/index'
  get 'departures/departure_matrix'

Departures View

The view looks a lot like all the other views in this book. I pass the data route into the makeChordChart() function so we can use that it for multiple chord diagrams. This code goes in app/views/departures/index.html.erb:

<div id="chart"></div>

$(document).on('ready page:load', function(event) {
  // apply non-idempotent transformations to the body

We also need to include the D3 library in the application layout (app/views/layouts/application.html.erb). Put this before the application’s JavaScript is loaded:

<%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js' %>

Departures Style

The stylesheet looks very similar to the other stylesheets. Put this code in app/assets/stylesheets/departures.scss:

@import url(http://fonts.googleapis.com/css?family=PT+Serif|PT+Serif:b|PT+Serif: i|PT+Sans|PT+Sans:b);

body {
  background: #fcfcfa;
  color: #333;
  font-family: "PT Serif", serif;
  margin: 1em auto 4em auto;
  position: relative;
  width: 960px;

svg {
  font: 10px sans-serif;

#circle circle {
  fill: none;
  pointer-events: all;

.group path {
  fill-opacity: .5;

path.chord {
  stroke: #000;
  stroke-width: .25px;

#circle:hover path.fade {
  display: none;
  • + Share This
  • 🔖 Save To Your Account