Learning Goals 🎯

  1. Understand how we can keep data around even after our webserver turns off
  2. Understand the structure of a database and how it can represent our data
  3. Be able to utilize Ruby helper functions to create and interact with a model

Prerequisites 🤔

In the Lab 3 and Homework 3, we kept track of the cities that the user had created using a class defined in City.rb and a static variable $cities. The problem with this, that you likely noticed while working on the homework, is that whenever you saved changes to a file and your server restarted, all your cities went away!

Variables that are created while the program runs are always temporary. When the program stops running, those variables get deleted. The topic of today's lecture is persistence: how do we keep things around? And how do we access our data quickly and effectively?

Persistent Data Storage!

One intuitive solution to the problem of keeping things around is to save it in a file outside of the code! A high level, naive example of this idea looks like this: whenever we call City.new, we'll create a file called city1.txt to save the data. And whenever we start our web server, we'll load in all the city files that past programs have created.

The problem with this, however, is that reading text files and saving to them is pretty slow. Additionally, as we have 100s of cities or 1,000,000s of cities, we're going to have a huge mess of files. The solution: instead of a simple .txt file to store our cities and other types of data, we'll put them in something we call a database!

A database is a simple concept built with some complex architecture. In short, a database is a collection of tables.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/68ff4254-afdf-4996-ba9c-1b7121c056e2/Untitled.png

These tables look exactly like the ones we learned about in primary school: there are columns and rows. Each column represents one "field", and each row represents a "record", containing a value for each field. In databases, we use a table for each kind of model or object we want to store! Before we talk about an app with multiple tables, let's start with an app that just has one: Homework 2!