Other Pages

Creating A Migration

Goals

    Topics
    id
    title
    description

    The suggestotron has a list of topics that people can vote on. We'll store our topics in the database. In this step you'll do the following:

  • Create a simple Table in the database for topics with a title and a description

  • Automatically generate the corresponding Scaffold in Rails (namely, the Model, the View, and the Controller).

Steps

Step 1

Option 1.1: Without Docker

Type this in the terminal:
rails generate scaffold topic title:string description:text

Option 1.2: With Docker

Type this in the terminal:
docker-compose run web rails generate scaffold topic title:string description:text
  • generate scaffold tells Rails to create everything necessary to get up and running with topics.
  • topic tells Rails the name of the new model.
  • title:string says that topics have a title, which is a "string".
  • description:text says that topics have a description which is a "text". A "text" is like a "string" that might be very long.

Step 2

Option 2.1: Without Docker

Type this in the terminal:
rails db:migrate

Option 2.2: With Docker

Type this in the terminal:
docker-compose run web rails db:migrate

This tells Rails to update the database to include a table for our new model.

Explanation

Databases don't create tables by themselves - they need instructions.

One of the files the scaffold command created will be named something like db/migrate/20140515115208_create_topics.rb. The numbers in the name are the date and time the file was made, so yours will be named differently.

The file contains Ruby code that describes what the table will look like. This is called a migration file. It tells the database how to transform itself into the new configuration.

class CreateTopics < ActiveRecord::Migration
  def change
    create_table :topics do |t|
      t.string :title
      t.text :description

      t.timestamps
    end
  end
end

rails db:migrate is a task provided by the Rails framework. It uses the migration file we just created (db/migrate/201xxxxxxxxxxx_create_topics.rb) to change the database. docker-compose run web <commands> is a way to run commands in docker web service we specified in docker-compose.yml earlier.

Explanation

Here, rails db:migrate is a command provided by the Rails framework. It uses the migration file we just created (db/migrate/201xxxxxxxxxxx_create_topics.rb) to change the database. Database migration files can be crucial to code collaboration. docker-compose run web <commands> is a way to run commands in docker web service we specified in docker-compose.yml earlier.

You can run rails -T to see a list of all the rails commands your app currently responds to, along with a short description of each task.

Next Step: