Note: This post is intended as a supplement to WTF Just Happened? A Quick Tour of Your First Rails App.
Database Migrations
When we need to make changes to our database schema (adding or modifying a table), we do so with an Active Record migration. A migration file is provided for you when you run rails generate scaffold Post
, or you can create your own by running rails generate migration
.
Below is the migration file that was created for us when we ran rails generate scaffold Post title:string body:text
.
ruby
class CreatePosts < ActiveRecord::Migration[5.0]
def change
create_table :posts do |t|
t.string :title
t.text :body
t.timestamps
end
end
end
The migration file is named 20170124022430_create_posts.rb
. Rails named it create_posts
because that is descriptive of its behaviour. It appended a datetime stamp so we can retrieve all migration files in the order in which they were created. Should Rails ever need to revert the database to a point in time, it can do so because we have this timeline built into the naming of the migration files.
When a migration is run (with the command rails db:migrate
), the database schema is updated. Details of the schema can be found in the file app/db/schema.rb
.
Below is the contents of schema.rb
after we have run rails generate scaffold Post title:string body:text
:
ruby
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170124022430) do
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
You will note that, in addition to the specified body
and title
attributes, Rails has provided us with two datetime stamps; created_at
and updated_at
. These record when the record was first created, and when it was last updated. Rails manages these values for us.