Home > Articles

The Chord Diagram

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

Departures App

Now that you have the data files it’s time to start working on the app. Create a new Rails app that uses Postgres as the database:

rails new departures --skip-bundle -d postgresql

You can look in Appendix A, “Ruby and Rails Setup,” for more information on how I generally create and configure a new Rails app. Create a new folder, db/data_files, move the two CSV files in there, and don’t forget to run rake db:create.


Before we dive into the departures, we need to load some of the related data. As you surely know, a flight begins and ends at an airport. We will use the file provided with the data challenge to load our airports.

Generate the Model

Create the Airport model and migration as follows:

rails generate model airport iata:string{4}:uniq airport   city state country lat:float long:float

That will give you an Airport model and also the migration to create the airports table. We specify that we want the length of the iata field to be no more than 4 characters, and we also want to index that field.

Load the Data

There are a lot of airports, but the data file is not very large. We can use Ruby’s built-in CSV library to read and convert the data, and we can use ActiveRecord to create new records. I use the same sort of rake task as in previous chapters, namespaced in the db:seed namespace.

I am generally not a fan of using “long” as an abbreviation for longitude, but that is what was in the data file. For this file and the next I wanted to keep the field names and header names in sync so that I could show the header converter in action. It takes the header field, downcases it, and then symbolizes it. The beauty of that is that you can take the row as you read it in and convert it to a hash that ActiveRecord understands in a create statement. The keys do not need to be converted to symbols for ActiveRecord to understand them, but I like my keys as symbols.

require 'csv'
CSV::Converters[:blank_to_nil] = lambda do |field|
  field && field.empty? ? nil : field

namespace :db do
  namespace :seed do
    desc "Import airport data"
    task :import_airports => :environment do
      if Airport.count == 0
        filename     = Rails.root.join('db', 'data_files', 'airports.csv')
        fixed_quotes = File.read(filename).gsub(/\\"/,'""')
        CSV.parse(fixed_quotes, :headers => true, :header_converters => :symbol, :converters => [:blank_to_nil]) do |row|

The really cool thing here is that the CSV library can understand how to do simple transformations as it reads the data. It can automatically convert fields to integer (any field that Integer() would accept), float (any field Float() accepts), date (Date::parse()), datetime (DateTime::parse()), and any combination of these. You can also create your own in addition to what the standard library offers, which is what we do with :blank_to_nil.

We also needed to clean the data a little before we could feed it into CSV. The CSV library expects quotes that are within strings to be escaped differently than the way they were escaped in the data. CSV will consider a double sequence of the quote character to be an escaped quote.


The carriers.csv file is the list of all the airlines. There are a lot of airlines, but the CSV file is not too large. This airline file also works nicely with the departure data.

Generate the Model

This model is a lot simpler with only two fields. We do the same sort of thing that we did for Airports:

rails g model carrier code:string{7}:uniq description

Load the Data

The carrier file is also not a very large file, so we can use CSV and ActiveRecord again to load the data.

desc "Import airline/carrier data"
task :import_carriers => :environment do
  if Carrier.count == 0
    filename = Rails.root.join('db', 'data_files', 'carriers.csv')
    CSV.foreach(filename, :headers => true, :header_converters => :symbol) do |row|

We can run the migration and rake task together:

bundle exec rake db:migrate db:seed:import_carriers


The last file you need to grab, if you haven’t already, is the 1999 departures data (http://stat-computing.org/dataexpo/2009/the-data.html). The DataExpo site gives a nice database schema for a SQLite database. Even though we are using Postgres, we can still use that for guidance. Unfortunately, the data is not clean. The Airline IATA code (UniqueCarrier) is sometimes too long for the field. Rather than modify the data, we will make the field long enough to support the data.

Generate the Model

There are a lot of fields, and there is a lot of data. We are going to need to do things a little differently here. We will create the model and migration using this generator:

rails g model departure year:integer:index month:integer   day_of_month:integer day_of_week:integer dep_time:integer   crs_dep_time:integer arr_time:integer crs_arr_time:integer   unique_carrier:string{6}:index flight_num:integer   tail_num:string{8} actual_elapsed_time:integer   crs_elapsed_time:integer air_time:integer arr_delay:integer   dep_delay:integer origin:string{3}:index dest:string{3}:index   distance:integer taxi_in:integer taxi_out:integer   cancelled:boolean:index cancellation_code:string{1}   diverted:boolean carrier_delay:integer weather_delay:integer   nas_delay:integer security_delay:integer   late_aircraft_delay:integer

Load the Data

This is a large data file, so we are going to optimize the load and use raw SQL instead of ActiveRecord to create these records.

Taking a note from Sandi Metz in Practical Object-Oriented Design in Ruby (POODR), I’ve abstracted out the data sanitation to a module. I put this in a file called db_sanitize.rb in the lib directory:

module DBSanitize
  def string(value)
    value.gsub!(/'/, '') unless value.nil?
    value.nil? ? 'NULL' : "'#{value}'"
  def integer(value)
    value.nil? ? 'NULL' : Integer(value)
  def boolean(value)
    value == '1'

I like this a lot better. Note that this code is not automatically loaded, so you have to require the file before including it. I put this at the top of the rake file under the CSV require statement:

require 'db_sanitize'
include DBSanitize

Now we can sanitize (clean) our data as we read it. I tested bulk insert versus inserting one record at a time with this data. I was surprised to see that the bulk insert did not save any time. Here is the rake task to import the departure data:

CSV::Converters[:na_to_nil] = lambda do |field|
  field && field == "NA" ? nil : field
desc "Import flight departures data"
task :import_departures => :environment do
  if Departure.count == 0
    filename  = Rails.root.join('db', 'data_files', '1999.csv')
    timestamp = Time.now.to_s(:db)
      :headers           => true,
      :header_converters => :symbol,
      :converters        => [:na_to_nil]
    ) do |row|
      puts "#{$.} #{Time.now}" if $. % 10000 == 0
      data = {
        :year                => integer(row[:year]),
        :month               => integer(row[:month]),
        :day_of_month        => integer(row[:dayofmonth]),
        :day_of_week         => integer(row[:dayofweek]),
        :dep_time            => integer(row[:deptime]),
        :crs_dep_time        => integer(row[:crsdeptime]),
        :arr_time            => integer(row[:arrtime]),
        :crs_arr_time        => integer(row[:crsarrtime]),
        :unique_carrier      => string(row[:uniquecarrier]),
        :flight_num          => integer(row[:flightnum]),
        :tail_num            => string(row[:tailnum]),
        :actual_elapsed_time => integer(row[:actualelapsedtime]),
        :crs_elapsed_time    => integer(row[:crselapsedtime]),
        :air_time            => integer(row[:airtime]),
        :arr_delay           => integer(row[:arrdelay]),
        :dep_delay           => integer(row[:depdelay]),
        :origin              => string(row[:origin]),
        :dest                => string(row[:dest]),
        :distance            => integer(row[:distance]),
        :taxi_in             => integer(row[:taxiin]),
        :taxi_out            => integer(row[:taxiout]),
        :cancelled           => boolean(row[:cancelled]),
        :cancellation_code   => string(row[:cancellationcode]),
        :diverted            => boolean(row[:diverted]),
        :carrier_delay       => integer(row[:carrierdelay]),
        :weather_delay       => integer(row[:weatherdelay]),
        :nas_delay           => integer(row[:nasdelay]),
        :security_delay      => integer(row[:securitydelay]),
        :late_aircraft_delay => integer(row[:lateaircraftdelay]),
        :created_at          => string(timestamp),
        :updated_at          => string(timestamp)
      sql = "INSERT INTO departures (#{data.keys.join(',')})"
      sql += " VALUES (#{data.values.join(',')})"

Run the migration and rake task (bundle exec rake db:migrate db:seed:import_departures). The departures data took about a half hour to load on my computer. Maybe (hopefully) yours is faster than mine. Alternately I created a dump file using pg_dump that you can load a little quicker:

pg_restore -v -d departures_development -j3 db/data_files/departures.

I feel inclined to point out, as a matter of perspective, that these immense file loads are not something that you would do in production very often. In the “real world” you’d be accumulating these data gradually over time. In essence we are playing catch-up with those production apps.

Foreign Keys

Now that we have the data loaded there is one more thing I want to do with the departures table. We can use the Rails generator to create a migration (rails g migration AddForeignKeysToDepartures). Here are contents of the change method:

add_foreign_key :departures, :carriers, :column => :unique_carrier, :primary_key => :code
add_foreign_key :departures, :airports, :column => :origin, :primary_key => :iata
add_foreign_key :departures, :airports, :column => :dest, :primary_key => :iata

Why did we do this when we add the relationships in the models with belongs_to and has_many, you ask? Doing those things is definitely a good idea. However, neither of them are absolute safeguards. To truly enforce referential integrity, you have to actually enforce referential integrity. We could have done this before loading the data, but checking every record on insert makes data loads take a lot longer. Removing foreign keys and indexes for a large data load is a common strategy. Just remember to add them back!

The other thing to note is that the records for those foreign keys must already exist. That is why we loaded the airlines and carriers first.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020