0
0
Ruby on Railsframework~30 mins

Adding and removing columns in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Adding and Removing Columns in Rails
📖 Scenario: You are working on a Rails app that manages a list of books. You need to update the database to add a new column for the book's genre and later remove the published_year column.
🎯 Goal: Create a Rails migration to add a genre column of type string to the books table, then create another migration to remove the published_year column from the same table.
📋 What You'll Learn
Create a migration file to add a genre column of type string to the books table
Create a migration file to remove the published_year column from the books table
Use the correct Rails migration methods add_column and remove_column
Name the migration classes correctly following Rails conventions
💡 Why This Matters
🌍 Real World
Adding and removing columns is a common task when evolving a Rails app's database to support new features or remove outdated data.
💼 Career
Rails developers frequently write migrations to update database schemas safely and maintain data integrity during app development.
Progress0 / 4 steps
1
Create migration to add genre column
Create a migration class called AddGenreToBooks that inherits from ActiveRecord::Migration[7.0]. Inside the change method, add a genre column of type string to the books table using add_column.
Ruby on Rails
Need a hint?

Use add_column :books, :genre, :string inside the change method.

2
Create migration to remove published_year column
Create a migration class called RemovePublishedYearFromBooks that inherits from ActiveRecord::Migration[7.0]. Inside the change method, remove the published_year column from the books table using remove_column.
Ruby on Rails
Need a hint?

Use remove_column :books, :published_year inside the change method.

3
Add migration timestamps
Add the timestamps method call inside the change method of the AddGenreToBooks migration class to track when records are created or updated.
Ruby on Rails
Need a hint?

Call timestamps inside the change method to add created_at and updated_at columns.

4
Add reversible migration for removing column
Modify the change method in the RemovePublishedYearFromBooks migration class to use reversible with remove_column and add_column so the migration can be rolled back safely. Remove the timestamps call from the AddGenreToBooks migration.
Ruby on Rails
Need a hint?

Use reversible do |dir| with dir.up and dir.down blocks to safely remove and add back the column.

Remove the timestamps call from the first migration.