Adding Columns to Tables with the Migration Generator

12:11 PM EDT Monday, April 21 2008

I just stumbled upon a neat little Rails feature and figured I'd share with the world. I'm working on a Facebook application and I'm going through some of the examples in Developing Facebook Platform Applications with Rails. In chapter 4, one of the tasks is:

Let's add a boolean hit column to our attack model. I'll wait while you create that migration.

It doesn't tell you how to do that, which I like. This is a simple enough task the reader should be able to do in their own, no need to clutter up the book with the code.

So I set out to do that, but for whatever reason my mind is in a bit of a fog today. I don't what it is, I've been making an inordinate number of typos. So when my fingers went to type the command to generate the migration, I just instinctively did this:

script/generate migration add_hit_to_attack hit:boolean

I accidentally added the hit:boolean column specification as if this were a script/generate model Whatever command. But it turns out Rails is able to read my mind. I opened up the migration file that was generated and there was this:

class AddHitToAttack < ActiveRecord::Migration
  def self.up
    add_column :attacks, :hit, :boolean
  end

  def self.down
    remove_column :attacks, :hit
  end
end

The code to add the column was already there. I checked the docs and sure enough there is support for this naming convention:

You can name your migration in either of these formats to generate add/remove
column lines from supplied attributes: AddColumnsToTable or RemoveColumnsFromTable

Example:
`./script/generate migration AddSslFlag`

With 4 existing migrations, this creates the AddSslFlag migration in
db/migrate/005_add_ssl_flag.rb

`./script/generate migration AddTitleBodyToPost title:string body:text published:boolean`

This will create the AddTitleBodyToPost in db/migrate/005_add_title_body_to_post.rb with
this in the Up migration:

  add_column :posts, :title, :string  
  add_column :posts, :body, :text  
  add_column :posts, :published, :boolean

And this in the Down migration:

  remove_column :posts, :published  
  remove_column :posts, :body  
  remove_column :posts, :title

Posted in  | Tags Rails, Migrations, Ruby

Comments Feed

Add a Comment