advertisement

Print

Cookin' with Ruby on Rails - May
Pages: 1, 2, 3, 4, 5, 6

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."

Generate migration file
Figure 16. (Click to enlarge.)

And now we'll open the migration file...

Add instructions to migration file
Figure 17.

...and add the instructions we want Rails to follow when we run this migration.

Migration file content
Figure 18. (Click to enlarge.)

And now we run the migration.

Run the "add name" migration
Figure 19. (Click to enlarge.)

And when we look at the database we see this.

Update database
Figure 20. (Click to enlarge.)

And when we look at the schema.rb file we see that Rails has modified it, too.

Modified schema file
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,

Contributor email migration
Figure 22. (Click to enlarge.)

add the instructions to move forward or backward from this version of the schema,

Add email migration file content
Figure 23. (Click to enlarge.)

run the migration,

Rake the add email migration
Figure 24. (Click to enlarge.)

and voila!  We have a new database structure.

Email added to database
Figure 25. (Click to enlarge.)

Pages: 1, 2, 3, 4, 5, 6

Next Pagearrow