0
0
Ruby on Railsframework~30 mins

Why migrations version the database in Ruby on Rails - See It in Action

Choose your learning style9 modes available
Why Migrations Version the Database
📖 Scenario: You are building a simple blog application using Rails. You want to keep track of changes to your database structure over time so that your team can work together smoothly and avoid conflicts.
🎯 Goal: Understand why Rails migrations use version numbers to manage database changes and how this helps keep the database schema consistent.
📋 What You'll Learn
Create a migration file with a specific version number
Add a configuration variable to track the current schema version
Write code to apply migrations in order based on version numbers
Complete the migration setup to ensure database consistency
💡 Why This Matters
🌍 Real World
In real projects, Rails migrations help teams safely update the database structure as the app evolves.
💼 Career
Understanding migration versioning is essential for Rails developers to manage database changes and collaborate effectively.
Progress0 / 4 steps
1
Create a migration file with a version number
Create a migration file named 20240601010101_create_posts.rb with a class called CreatePosts that inherits from ActiveRecord::Migration[7.0].
Ruby on Rails
Need a hint?

Migration files have a timestamp prefix as their version number. The class inherits from ActiveRecord::Migration with the Rails version in brackets.

2
Add a configuration variable to track schema version
Add a variable called ActiveRecord::SchemaMigration.version and set it to the string "20240601010101" to represent the current migration version.
Ruby on Rails
Need a hint?

The schema version is stored as a string matching the migration timestamp to track which migrations have been applied.

3
Apply migrations in order using version numbers
Write a method called apply_migrations that takes a list of migration versions and applies only those with a version greater than ActiveRecord::SchemaMigration.version.
Ruby on Rails
Need a hint?

Compare each migration version to the current schema version and apply only newer migrations.

4
Complete migration setup for database consistency
Add a final line to call apply_migrations with the list ["20240601010101", "20240602020202"] to simulate applying migrations in order.
Ruby on Rails
Need a hint?

Calling apply_migrations with a list of versions simulates running migrations in the correct order.