Bird
Raised Fist0
Ruby on Railsframework~20 mins

Creating migrations in Ruby on Rails - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Migration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the effect of this migration code?
Consider this Rails migration code snippet:
class AddAgeToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :age, :integer, default: 18
  end
end

What will be the result after running this migration?
Ruby on Rails
class AddAgeToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :age, :integer, default: 18
  end
end
ACreates a new table called 'age' with integer type
BRemoves the 'age' column from 'users' table
CChanges the 'age' column type to string in 'users' table
DAdds an integer column 'age' to 'users' table with default value 18 for new records
Attempts:
2 left
💡 Hint
Think about what add_column does and the effect of default value.
📝 Syntax
intermediate
2:00remaining
Which migration code will create a table with a primary key?
You want to create a new table 'products' with columns 'name' (string) and 'price' (decimal). Which migration code correctly creates this table with an id primary key?
A
create_table :products do |t|
  t.string :name
  t.decimal :price
end
B
create_table :products, id: false do |t|
  t.string :name
  t.decimal :price
end
C
create_table :products, primary_key: :product_id do |t|
  t.string :name
  t.decimal :price
end
D
create_table :products, id: true do |t|
  t.string :name
  t.decimal :price
end
Attempts:
2 left
💡 Hint
By default, create_table adds an id primary key unless id: false is specified.
🔧 Debug
advanced
2:00remaining
Why does this migration raise an error?
Given this migration:
class ChangePriceTypeInProducts < ActiveRecord::Migration[7.0]
  def change
    change_column :products, :price, :string
  end
end

Running this migration raises an error. What is the cause?
Ruby on Rails
class ChangePriceTypeInProducts < ActiveRecord::Migration[7.0]
  def change
    change_column :products, :price, :string
  end
end
AThe :string type is invalid for change_column
Bchange_column cannot be used inside the change method because it is irreversible
CThe migration file is missing a version number in the class inheritance
DThe :price column does not exist in the products table
Attempts:
2 left
💡 Hint
Think about whether change_column can be reversed automatically.
❓ state_output
advanced
2:00remaining
What is the state of the database after this migration?
After running this migration:
class CreateOrders < ActiveRecord::Migration[7.0]
  def change
    create_table :orders do |t|
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
  end
end

Which statement is true about the 'orders' table?
Ruby on Rails
class CreateOrders < ActiveRecord::Migration[7.0]
  def change
    create_table :orders do |t|
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
  end
end
AThe 'orders' table has no timestamps columns
BThe 'orders' table has a 'user' column storing user names
CThe 'orders' table has a 'user_id' column with a foreign key constraint to 'users' table
DThe 'orders' table has a 'user_id' column but no foreign key constraint
Attempts:
2 left
💡 Hint
t.references adds a column with _id suffix and foreign_key: true adds a constraint.
🧠 Conceptual
expert
2:00remaining
What happens if you rollback a migration that adds a column with default value?
You run a migration that adds a column 'status' with default 'pending' to 'tasks' table. Then you rollback this migration. What is the state of the 'tasks' table after rollback?
AThe 'status' column is removed from the 'tasks' table
BThe 'status' column remains but default value is removed
CThe 'status' column remains with default 'pending'
DThe rollback fails because default values cannot be removed
Attempts:
2 left
💡 Hint
Rollback reverses the migration changes, removing added columns.

Practice

(1/5)
1. What is the main purpose of a migration in Rails?
easy
A. To change the database structure step-by-step
B. To write application business logic
C. To style the user interface
D. To manage user sessions

Solution

  1. Step 1: Understand what migrations do

    Migrations are used to modify the database schema in a controlled way.
  2. Step 2: Identify the correct purpose

    Changing database structure step-by-step matches the role of migrations.
  3. Final Answer:

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

    Migrations = Change database structure [OK]
Hint: Migrations change database structure, not app logic or UI [OK]
Common Mistakes:
  • Confusing migrations with application code
  • Thinking migrations handle UI or sessions
2. Which command correctly generates a migration to add a title column of type string to the posts table?
easy
A. rails generate migration AddColumn posts title:string
B. rails generate migration CreatePosts title:string
C. rails generate migration AddTitleToPosts title:string
D. rails generate migration AddTitle posts string

Solution

  1. Step 1: Identify the correct migration naming pattern

    Adding a column uses 'AddColumnNameToTableName' format, here 'AddTitleToPosts'.
  2. Step 2: Check the command syntax

    The correct syntax is 'rails generate migration AddTitleToPosts title:string'.
  3. Final Answer:

    rails generate migration AddTitleToPosts title:string -> Option C
  4. Quick Check:

    Correct migration command = rails generate migration AddTitleToPosts title:string [OK]
Hint: Use 'AddColumnToTable' naming with column:type [OK]
Common Mistakes:
  • Using 'CreatePosts' instead of 'AddTitleToPosts'
  • Wrong order or missing 'To' in migration name
  • Incorrect column type syntax
3. Given this migration code:
class AddAgeToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :age, :integer
  end
end

What happens after running rails db:migrate?
medium
A. Raises a syntax error due to missing migration version
B. Removes the 'age' column from the 'users' table
C. Creates a new 'users' table with an 'age' column
D. Adds an integer column named 'age' to the 'users' table

Solution

  1. Step 1: Analyze the migration class

    The migration inherits from ActiveRecord::Migration[7.0] and defines a change method adding a column.
  2. Step 2: Understand the add_column method

    It adds an integer column 'age' to the existing 'users' table.
  3. Final Answer:

    Adds an integer column named 'age' to the 'users' table -> Option D
  4. Quick Check:

    add_column adds column = Adds an integer column named 'age' to the 'users' table [OK]
Hint: add_column adds a new column to existing table [OK]
Common Mistakes:
  • Confusing add_column with remove_column
  • Thinking it creates a new table
  • Missing migration version causes error (not here)
4. You wrote this migration:
class AddEmailToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :email
  end
end

What is the problem when running rails db:migrate?
medium
A. Syntax error due to missing 'def up' method
B. Missing column type for 'email' causes an error
C. Migration runs successfully without issues
D. Table 'users' does not exist error

Solution

  1. Step 1: Check add_column method usage

    add_column requires three arguments: table name, column name, and column type.
  2. Step 2: Identify missing argument

    The migration misses the column type for 'email', causing an error.
  3. Final Answer:

    Missing column type for 'email' causes an error -> Option B
  4. Quick Check:

    add_column needs type argument [OK]
Hint: Always specify column type with add_column [OK]
Common Mistakes:
  • Omitting column type argument
  • Assuming migration runs without errors
  • Confusing change method with up/down methods
5. You want to create a migration that renames the column username to login in the accounts table. Which migration code correctly does this?
hard
A. class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change rename_column :accounts, :username, :login end end
B. class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change change_column :accounts, :username, :login end end
C. class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change rename_table :username, :login end end
D. class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change remove_column :accounts, :username add_column :accounts, :login, :string end end

Solution

  1. Step 1: Identify the correct method to rename a column

    Rails provides rename_column to rename columns in a table.
  2. Step 2: Check each option's method

    class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change rename_column :accounts, :username, :login end end uses rename_column correctly; class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change change_column :accounts, :username, :login end end wrongly uses change_column; class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change rename_table :username, :login end end tries to rename tables; class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change remove_column :accounts, :username add_column :accounts, :login, :string end end removes and adds columns instead of renaming.
  3. Final Answer:

    Use rename_column :accounts, :username, :login in change method -> Option A
  4. Quick Check:

    rename_column renames columns = class RenameUsernameToLogin < ActiveRecord::Migration[7.0] def change rename_column :accounts, :username, :login end end [OK]
Hint: Use rename_column to rename columns, not change_column [OK]
Common Mistakes:
  • Using change_column instead of rename_column
  • Trying to rename tables instead of columns
  • Removing and adding columns instead of renaming
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