Bird
Raised Fist0
Ruby on Railsframework~10 mins

Adding and removing columns in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Adding and removing columns
Generate Migration
↓
Edit Migration File
↓
Run Migration
↓
Database Schema Updated
↓
Use Updated Model
The flow shows creating a migration, editing it to add or remove columns, running it to update the database, and then using the updated model.
Execution Sample
Ruby on Rails
class AddAgeToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :age, :integer
  end
end
This migration adds an integer column 'age' to the 'users' table.
Execution Table
StepActionMigration File ContentDatabase Schema ChangeResult
1Generate migrationclass AddAgeToUsers < ActiveRecord::Migration[7.0] def change end endNo change yetMigration file created
2Edit migrationclass AddAgeToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :age, :integer end endNo change yetMigration file updated with add_column
3Run migrationSame as step 2users table gains 'age' column of type integerSchema updated, column added
4Use modelN/ASchema includes 'age' columnCan now read/write 'age' attribute on User
5Generate remove migrationclass RemoveAgeFromUsers < ActiveRecord::Migration[7.0] def change remove_column :users, :age end endNo change yetMigration file created to remove column
6Run remove migrationSame as step 5users table loses 'age' columnSchema updated, column removed
7Use modelN/ASchema no longer has 'age' columnAccessing 'age' attribute will fail
8ExitN/ANo further changesProcess complete
💡 All migrations run, database schema updated accordingly
Variable Tracker
VariableStartAfter Step 3After Step 6Final
users table columnsid, name, emailid, name, email, ageid, name, emailid, name, email
Key Moments - 3 Insights
Why doesn't the database schema change immediately after generating the migration file?
Because generating the migration only creates a file; the schema changes only after running the migration (see execution_table step 3).
What happens if you try to access a removed column in the model?
Accessing a removed column will cause errors because the database no longer has that column (see execution_table step 7).
Why do we specify the column type when removing a column?
Specifying the type helps Rails know exactly which column to remove, ensuring safe migration (see execution_table step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the 'age' column actually added to the database?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Check the 'Database Schema Change' column in the execution_table rows
According to the variable tracker, what columns does the users table have after step 6?
Aid, name, email, age
Bid, name, email, age, created_at
Cid, name, email
Dage only
💡 Hint
Look at the 'After Step 6' column in variable_tracker
If you forgot to run the migration after editing the migration file, what would happen?
AThe schema would remain unchanged
BThe database schema would update automatically
CThe migration file would run on its own
DRails would throw an error immediately
💡 Hint
Refer to execution_table steps 2 and 3 to see when schema changes
Concept Snapshot
Adding and removing columns in Rails:
- Generate a migration file with 'rails generate migration'
- Edit the migration to add_column or remove_column
- Run 'rails db:migrate' to update the database
- Use the updated model with new or removed columns
- Always specify column type when removing columns
Full Transcript
In Rails, to add or remove columns from a database table, you first generate a migration file. This file is like a recipe for changes but does not affect the database until you run it. You then edit the migration file to specify adding or removing a column, including the column name and type. Running the migration applies these changes to the database schema. After that, your Rails model reflects the updated schema, allowing you to use the new or removed columns in your code. Remember, generating a migration file alone does not change the database; running the migration is necessary. Also, when removing columns, specifying the column type helps Rails safely identify the column to remove.

Practice

(1/5)
1. What is the primary purpose of adding a column in a Rails migration?
easy
A. To rename an existing table
B. To delete old data from the database
C. To create a new database table
D. To store new types of data in an existing database table

Solution

  1. Step 1: Understand what adding a column means

    Adding a column means extending an existing table to hold more data fields.
  2. Step 2: Identify the purpose of adding columns in Rails migrations

    It allows storing new types of data without creating a new table or deleting data.
  3. Final Answer:

    To store new types of data in an existing database table -> Option D
  4. Quick Check:

    Adding columns = storing new data [OK]
Hint: Adding columns means expanding tables to hold new data [OK]
Common Mistakes:
  • Confusing adding columns with creating tables
  • Thinking adding columns deletes data
  • Mixing up adding columns with renaming tables
2. Which of the following is the correct syntax to add a column named age of type integer to the users table in a Rails migration?
easy
A. add_column :users, :age, :integer
B. add_column users, age, integer
C. add_column(:users, :age, integer)
D. add_column(:users, age, :integer)

Solution

  1. Step 1: Recall the correct method signature for adding a column

    The method is add_column(table_name, column_name, type) with symbols for names.
  2. Step 2: Check each option for correct syntax

    add_column :users, :age, :integer uses symbols and correct commas: add_column :users, :age, :integer.
  3. Final Answer:

    add_column :users, :age, :integer -> Option A
  4. Quick Check:

    Correct syntax uses symbols and commas [OK]
Hint: Use symbols and commas: add_column :table, :column, :type [OK]
Common Mistakes:
  • Omitting colons before symbols
  • Using parentheses incorrectly
  • Missing commas between arguments
3. Given this migration code:
class AddNicknameToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :nickname, :string
  end
end

What will happen after running rails db:migrate?
medium
A. An error will occur because the migration is missing a remove_column
B. The users table will be deleted
C. A new column 'nickname' of type string will be added to the users table
D. The nickname column will be removed from the users table

Solution

  1. Step 1: Understand the migration code

    The migration adds a string column called nickname to the users table inside the change method.
  2. Step 2: Know what rails db:migrate does

    It applies the change method, adding the new column to the database table.
  3. Final Answer:

    A new column 'nickname' of type string will be added to the users table -> Option C
  4. Quick Check:

    add_column in change adds the column [OK]
Hint: add_column inside change adds the column on migrate [OK]
Common Mistakes:
  • Thinking remove_column is required to add columns
  • Confusing add_column with deleting tables
  • Assuming migration deletes columns by default
4. You wrote this migration to remove the birthdate column from users:
class RemoveBirthdateFromUsers < ActiveRecord::Migration[7.0]
  def change
    remove_column :users, :birthdate
  end
end

When running rails db:migrate, you get an error. What is the likely cause?
medium
A. remove_column requires the column type as a third argument in change method
B. remove_column cannot be used inside change method
C. The migration class name is incorrect
D. You must use add_column to remove a column

Solution

  1. Step 1: Recall remove_column syntax in change method

    When using remove_column inside change, you must provide the column type as the third argument.
  2. Step 2: Check the migration code

    The code misses the column type, causing an error during migration.
  3. Final Answer:

    remove_column requires the column type as a third argument in change method -> Option A
  4. Quick Check:

    remove_column in change needs column type [OK]
Hint: Provide column type when removing columns in change method [OK]
Common Mistakes:
  • Omitting column type argument
  • Trying to remove columns with add_column
  • Misnaming migration class
5. You want to add a status column to orders with default value 'pending' and then remove the old_status column safely. Which migration code correctly does this?
hard
A. def change add_column :orders, :status, :string remove_column :orders, :old_status end
B. def change add_column :orders, :status, :string, default: 'pending' remove_column :orders, :old_status, :string end
C. def change add_column :orders, :status, :string, default: 'pending' remove_column :orders, :old_status end
D. def up add_column :orders, :status, :string, default: 'pending' remove_column :orders, :old_status, :string end def down remove_column :orders, :status add_column :orders, :old_status, :string end

Solution

  1. Step 1: Understand adding with default and removing columns safely

    Adding a column with default works in change. Removing a column in change requires the type for reversibility.
  2. Step 2: Analyze options for correctness and safety

    def change add_column :orders, :status, :string, default: 'pending' remove_column :orders, :old_status, :string end uses def change add_column :orders, :status, :string, default: 'pending' remove_column :orders, :old_status, :string end with default on add and type on remove for safe migration and rollback.
  3. Final Answer:

    def change add_column :orders, :status, :string, default: 'pending' remove_column :orders, :old_status, :string end -> Option B
  4. Quick Check:

    change method with type for remove and default for add [OK]
Hint: Use change with column type for safe remove_column [OK]
Common Mistakes:
  • Omitting column type when removing
  • Not providing default value when needed
  • Using change method without rollback safety
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