Topic: Database Migrations

Just starting out with Rails and have a question which probably has a pretty obvious answer to some people. I'm just playing with things at the moment and looking through the cookbook tutorial.

Right - I've created a new model using './script/generate model recipe' which has created my db/migrate/001_create_recipes.rb file. Now I've added a couple of fields and ran 'rake migrate' which has created the table and added the fields just fine.

However, what do I do if I wanted to add another field to this same table using migration?



Re: Database Migrations

You can create another migration like this (change the migration name to whatever you want):

./script/generate migration add_recipe_field

Then you can do this in the migration.

def self.up
  add_column :recipes, :my_field, :string

def self.down
  remove_column :recipes, :my_field

Railscasts - Free Ruby on Rails Screencasts

Re: Database Migrations

Thanks - so simple when you think about it...

Re: Database Migrations

Is there a limit on the number of migrations? I can just see things getting pretty messy after a while.

Re: Database Migrations

There's no limit.  However, in practice I'm hearing that a lot of projects will "clean up" their migrations just prior to a major release.

Lets say you've been developing your application for several weeks/months and you have 30-50 migrations, touching maybe 20 tables.  Some groups will collapse the migrations to either a) 1 migration per table, or b) a single migration that's basically a copy of schema.rb.  Going forward, they still use teeny-tiny migration to effect change to this new baseline and then at the next major milestone, recollapse.

Personally I think that the timing of the above story, which seems to be common, is a little off -- I wouldn't want to lose my rollback/forward ability until I was "certain" the release was "clean".  However if you have some "irreversible" migrations, then I don't see much harm in collapsing all the previous ones upto that point if that floats your boat.

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.