Store Jobs In The Database

Goals

  • Create a table in the database for jobs

  • Review what a database is

  • Learn what a migration file is

Discussion: Databases & SQL


Review how relational databases are structured, how we communicate with them?

  • How do you read data from a Database with SQL?
  • How do you read data from a Database with ActiveRecord?

Steps

Step 1: generate a jobs model and a jobs migration

In order to make it possible for users to create jobs,

  • we need a place to store the jobs (a table in the database)
  • we need Rails to know what a job is (a model)

We're going to use another Rails generator; this time to make our migration and model!

Type this in the shell:
rails g model job

(The g stands for generate, which has many more letters than is necessary to type.)

That generated two files: a migration and models/job.rb.

Find the migration file in your editor!

Step 2: add columns to the migration

Open up the migration file and you'll see the following:

class CreateJobs < ActiveRecord::Migration[5.0]
  def change
    create_table :jobs do |t|

      t.timestamps
    end
  end
end

Running this code will make a table in our database called jobs. Right now it just has the timestamps (created_at and updated_at), and the id as a primary key, because we did not specify any columns when we generated it.

What else should a job have? Let's start with a title and description.

Add the title and description so the migration file looks like this:

create_table :jobs do |t|
  t.string :title
  t.text :description
  t.timestamps
end

Step 3: create the table in the database

Now we need to execute the migration file, so that the database schema gets updated.

Type this in the shell:
rails db:migrate

This tells Rails to run any migration files that haven't already been run at some point in the past.

Discussion: Why do we use migrations?


Talk about the pros and cons of using migrations to update the database, instead of just updating the schema directly. Also, discuss what the database schema is!

(Pro-tip: never update the schema directly.)

Step 4: Check out the model

The migration we just ran updated the database, but that doesn't mean that we can talk to the database using Ruby yet. Look at the file app/models/job.rb.

The model is empty right now, but it will know how to talk to the database, and will know about the columns in the database, because it inherits from ApplicationRecord

Now would be a good time to commit to git

Next Step: