Migration Basics

Migrations are maintained in files stored in the db/migrate folder. Each file contains one more-or-less discrete set of changes to the underlying database. Unlike most of the code you write, migrations are not automatically run when you start up Rails, instead waiting for an explicit command from the rake tool.

Migration Files

Prior to Rails 2.1, migration files had relatively comprehensible names, such as 001_create_people.rb. Rails 2.1 brought a new naming convention, in which the first part of the name changed from being a sequential number to being a much longer timestamp, like 20080701211008_create_students.rb. The new wider names are incredibly annoying if you’re just one developer creating applications on a laptop with a narrow screen, but help avoid name collisions if you’re a developer working on a team where multiple people can check in their own migrations. (Perhaps the team developers have larger monitors as well?)

While you can create migration files by hand, if you’re going to work with migrations in the new world of timestamps, you should probably stick to using script/generate, which will handle all of that for you. Many script/generate calls will create migrations as part of their work toward creating a model and supporting infrastructure, but if you just want to create a blank migration, enter the command script/generate migration NameOfMigration, where NameOfMigration is a reasonably human-comprehensible description of what the migration is going ...

Get Learning Rails: Live Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.