Paul: So when we told it to generate the migration we called "BaselineSchema," it generated this file, prefixed it with "001_", and named it with underscores where we used CamelCase. OK. So what's this bought us?
CB: Glad you asked (he says with that grin CB gets when he's about to start showing off).
Let's just do a little pretend work so I can show you. Let's pretend Boss tells us "we need to be able to keep track of who contributed recipes to the site." So, after careful analysis of this requirement, you and I conclude that we need to add a column to the recipes table. Let's call it "contributor_name." We'll make it a string field, and give it a default value since we don't have the information for the existing records. What we want to do is "migrate" our database from its current structure to this new one, so we define a new migration. We do that the same way we did our initial migration: using the
script\generate migration command. To help us remember what the migration does, we'll name it something meaningful like "AddContributorName."
Figure 16. (Click to enlarge.)
And now we'll open the migration file...
...and add the instructions we want Rails to follow when we run this migration.
Figure 18. (Click to enlarge.)
And now we run the migration.
Figure 19. (Click to enlarge.)
And when we look at the database we see this.
Figure 20. (Click to enlarge.)
And when we look at the schema.rb file we see that Rails has modified it, too.
Figure 21. (Click to enlarge.)
Paul: Yeah. I see that it's changed the version number and added the contributor_name column.
CB: Exactly. Rails is now handling the database versioning for us. By showing us that this is
:version => 2, Rails is telling us that this schema includes all migrations up to the one that starts with the "002_" prefix. Let me add another migration real quick just so we can play with it a little more. So we'll pretend Boss comes in later and says "We need to keep an email address for the contributor, too." And again, after careful analysis of this new requirement, you and I decide we need to add another column to the Recipes table. Time for a new migration. After much deliberation, we decide to name our migration "AddContributorEmail."
So we generate the migration file,
Figure 22. (Click to enlarge.)
add the instructions to move forward or backward from this version of the schema,
Figure 23. (Click to enlarge.)
run the migration,
Figure 24. (Click to enlarge.)
and voila! We have a new database structure.
Figure 25. (Click to enlarge.)