Bird
Raised Fist0
Ruby on Railsframework~10 mins

Database folder and migrations in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Database folder and migrations
Create Migration File
↓
Write Schema Changes
↓
Run Migration Command
↓
Rails Updates Schema
↓
Database Structure Changes
↓
Migration Status Updated
Shows how a migration file is created, written, run, and applied to update the database schema.
Execution Sample
Ruby on Rails
class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :name
      t.timestamps
    end
  end
end
This migration creates a users table with a name column and timestamps.
Execution Table
StepActionFile/CommandEffectDatabase State
1Generate migration filerails generate migration CreateUsersCreates db/migrate/xxxx_create_users.rbNo users table yet
2Write migration codedb/migrate/xxxx_create_users.rbDefines users table with name and timestampsNo change yet
3Run migrationrails db:migrateRails runs migration codeUsers table created with columns: id, name, created_at, updated_at
4Update schema.rbAutomaticSchema file updated to reflect new tableSchema matches database
5Migration statusrails db:migrate:statusShows migration as upMigration applied successfully
6Exit-No more migrations to runDatabase schema up to date
💡 All migrations applied, database schema is current
Variable Tracker
VariableStartAfter Step 1After Step 3Final
users_tabledoes not existmigration file createdtable created in DBtable exists with columns
Key Moments - 2 Insights
Why doesn't the database change immediately after creating the migration file?
Creating the migration file only prepares the instructions. The database changes only after running 'rails db:migrate' as shown in step 3 of the execution_table.
What does the schema.rb file represent?
schema.rb is an auto-generated file that reflects the current database structure after migrations run, as seen in step 4 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the users table actually created in the database?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Check the 'Effect' and 'Database State' columns for when the table appears
According to variable_tracker, what is the state of users_table after step 1?
AMigration file created but table does not exist
BTable exists with columns
CTable created in DB
DNo users table yet
💡 Hint
Look at the 'After Step 1' column for users_table
If you skip running 'rails db:migrate', what will happen to the database?
ADatabase schema updates automatically
BDatabase remains unchanged
CSchema.rb updates but DB does not
DMigration status shows as up
💡 Hint
Refer to step 3 and the exit_note in execution_table
Concept Snapshot
Database folder holds migration files.
Migrations describe schema changes.
Run 'rails db:migrate' to apply changes.
Schema.rb reflects current DB structure.
Migration status shows applied migrations.
Full Transcript
In Rails, the database folder contains migration files that describe changes to the database structure. First, you generate a migration file which is just a set of instructions. Then you write the schema changes inside it, like creating tables or adding columns. When you run 'rails db:migrate', Rails executes these instructions and updates the actual database. After migration, Rails updates the schema.rb file to reflect the current database structure. You can check migration status to see which migrations have been applied. This process ensures your database matches your app's needs step-by-step.

Practice

(1/5)
1. What is the main purpose of the db/migrate folder in a Rails project?
easy
A. To store migration files that change the database structure step-by-step
B. To hold all the Ruby model files for the application
C. To keep the application configuration files
D. To store static assets like images and stylesheets

Solution

  1. Step 1: Understand the role of the db/migrate folder

    This folder contains migration files that describe changes to the database schema over time.
  2. Step 2: Differentiate from other folders

    Model files are in app/models, configs in config, and assets in app/assets.
  3. Final Answer:

    To store migration files that change the database structure step-by-step -> Option A
  4. Quick Check:

    Migration files = db/migrate folder [OK]
Hint: Migrations live in db/migrate to track database changes [OK]
Common Mistakes:
  • Confusing migrations with model files
  • Thinking assets or configs are in db/migrate
  • Assuming db/migrate holds seed data
2. Which command correctly generates a new migration file in Rails?
easy
A. rails new migration AddAgeToUsers age:integer
B. rails generate migration AddAgeToUsers age:integer
C. rails create migration AddAgeToUsers age:integer
D. rails make migration AddAgeToUsers age:integer

Solution

  1. Step 1: Recall the Rails command for generating migrations

    The correct command is rails generate migration followed by the migration name and fields.
  2. Step 2: Check the options for correct syntax

    Only rails generate migration AddAgeToUsers age:integer uses the exact Rails command syntax for migration generation.
  3. Final Answer:

    rails generate migration AddAgeToUsers age:integer -> Option B
  4. Quick Check:

    Use rails generate migration to create migrations [OK]
Hint: Use 'rails generate migration' to create migration files [OK]
Common Mistakes:
  • Using 'rails create' instead of 'rails generate'
  • Confusing 'rails new' with migration commands
  • Using 'rails make' which is invalid
3. Given this migration file content:
class CreateBooks < ActiveRecord::Migration[7.0]
  def change
    create_table :books do |t|
      t.string :title
      t.integer :pages
      t.timestamps
    end
  end
end

What will happen when you run rails db:migrate?
medium
A. Nothing happens because migrations only update existing tables
B. An error occurs because the migration syntax is wrong
C. The existing 'books' table will be deleted
D. A new table named 'books' with columns 'title', 'pages', and timestamps will be created

Solution

  1. Step 1: Analyze the migration code

    The migration defines creating a new table called 'books' with columns 'title' (string), 'pages' (integer), and timestamps.
  2. Step 2: Understand what rails db:migrate does

    It runs pending migrations, applying the changes to the database schema, here creating the 'books' table.
  3. Final Answer:

    A new table named 'books' with columns 'title', 'pages', and timestamps will be created -> Option D
  4. Quick Check:

    Create table migration runs successfully [OK]
Hint: Create_table migrations add new tables when migrated [OK]
Common Mistakes:
  • Thinking migration deletes tables
  • Assuming syntax error without checking code
  • Believing migrations only update, not create
4. You wrote this migration:
class AddEmailToUsers < ActiveRecord::Migration
  def change
    add_column :users, :email, :string
  end
end

But running rails db:migrate gives an error: undefined method 'add_column'. What is the likely cause?
medium
A. The migration class should inherit from ActiveRecord::Migration[7.0] but it does
B. The migration file is missing the def change method
C. The migration class is missing the version number in inheritance
D. The migration file name does not match the class name

Solution

  1. Step 1: Check the migration inheritance

    Rails 7 requires specifying the migration version in the class inheritance, e.g., ActiveRecord::Migration[7.0].
  2. Step 2: Identify the error cause

    If the version is missing or incorrect, Rails may not recognize migration methods like add_column, causing the error.
  3. Final Answer:

    The migration class is missing the version number in inheritance -> Option C
  4. Quick Check:

    Migration version number required for method recognition [OK]
Hint: Always specify migration version in class inheritance [OK]
Common Mistakes:
  • Ignoring migration version in class inheritance
  • Assuming method missing means syntax error
  • Not matching file name and class name
5. You want to rename a column username to login in the users table using a migration. Which migration code correctly does this?
hard
A. def change rename_column :users, :username, :login end
B. def change change_column :users, :username, :login end
C. def change remove_column :users, :username add_column :users, :login, :string end
D. def change rename_table :users, :login end

Solution

  1. Step 1: Understand the goal

    You want to rename a column, not change its type or remove and add a new one.
  2. Step 2: Identify the correct migration method

    rename_column changes a column's name safely without losing data.
  3. Step 3: Check options

    def change rename_column :users, :username, :login end uses rename_column :users, :username, :login, which is correct. def change change_column :users, :username, :login end wrongly uses change_column which changes type, not name. def change remove_column :users, :username add_column :users, :login, :string end removes and adds columns, which is risky. def change rename_table :users, :login end renames the whole table, not a column.
  4. Final Answer:

    def change rename_column :users, :username, :login end -> Option A
  5. Quick Check:

    Use rename_column to rename columns safely [OK]
Hint: Use rename_column to rename columns without data loss [OK]
Common Mistakes:
  • Using change_column to rename instead of change type
  • Removing and adding columns loses data
  • Confusing rename_table with rename_column
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard