Learning Goals 🎯

  1. Understand how to relate multiple models to eachother
  2. Be able to establish associations and validations at the model level
  3. Understand how migrations define our database and how to create them

Prerequisites 🤔

In the first part of this guide, we are simply going to be expanding on our initial discussion of models. We started by talking about how data is represented, and now we're going to talk about how we relate data together and the things Rails does to help us interact with our models.

Associations, Migrations, and Validations

Last week we discussed how our data lives in tables in a database. To review this concept, let's take a look at an example.

Cities

Here is a simple table representing our City model we have columns representing each data type, and rows representing each instance. To create this model in Rails, we'd run the command: rails generate model City name:string landmark:string population:integer.

This creates the table above in our database with three extra fields! id, which is a unique ID given to every model, and then created_at and updated_at which automatically get managed when you save to the database. Now that we've created the models in Rails, we can manipulate them in our controllers or in the Rails Console using simple commands like below:

# Creates AND saves a new city.
City.create name: "Berkeley", landmark: "Campanile", population: 20000

# Returns a list
City.where(name: "Berkeley")

# Returns the first city where this is true
City.find_by(landmark: "Campanile")

# Gets the first city in the database
City.first