Getting Started with Rails 7 Episode 3: Autoloading, Generate and Migrate a Model

Migration section in the Rails Guide

This is the 3rd video in the Getting Started with Rails 7 series. In this video Mike reviews the Autoloading section of the Getting Started with Rails guide and compares it to the NerdDice RubyGem project. Then he creates the Article model and explores the resulting Rails migration, the errors that occur when you have a pending migration and how to rollback a migration.

This video covers:

  • 00:00:10 Introduction
  • 00:00:58 Autoloading in Rails compared to requiring in other Ruby projects
  • 00:05:08 Generate the Article model
  • 00:08:07 Review the generated Rail migration file
  • 00:10:12 Demonstrate ActiveRecord::PendingMigrationError
  • 00:11:29 Run the create_articles Rails migration and look at the schema.rb file
  • 00:13:24 Rollback and re-run the migration to demonstrate what happens in schema and in application
  • 00:15:07 Discussion of alternatives for Rails migrations (self.up, self.down, ActiveRecord::IrreversibleMigration)
  • 00:16:27 Discussion of the value of Rails migrations compared to issuing the SQL commands in the database itself

To run a Rails migration:

bin/rails db:migrate

To rollback your last Rails migration:

# STEP=1 is implied if you leave it off. You can do more than one by changing the step number
bin/rails db:rollback STEP=1

If things get to a point where you are stuck in your development environment and you want to start over:

# WARNING: This will drop your database and lose all data! Don't do this in production!
# delete your database
bin/rails db:drop
# re-create your database
bin/rails db:create 
# run your migrations
bin/rails db:migrate
# run your database seed script in db/seeds.rb if applicable
bin/rails db:seed

If you want to go deeper into Rails migrations, you can check out the Active Record Migrations guide for Rails 7.

The code for this series is open source and available on GitHub. View the commit for this video here

, ,

Leave a Reply