I absolutely loves Rails 2.0 and the command line conveniences it provides for the RESTful scaffolding and models. Here’s a couple of tricks to generate a migration to quickly to add/remove columns from an existing table.
Assume you already have a table called ‘Users’. You would like to add a column called ‘title’ and another column called ‘email’. You can quickly create a migration from the command line using the following :
script/generate migration AddTitleEmailToUsers title:string email:string
The migration generated looks like this:
class AddTitleEmailToUsers < ActiveRecord::Migration
def self.up
add_column :users, :title, :string
add_column :users, :email, :string
end
def self.down
remove_column :users, :email
remove_column :users, :title
end
end
</pre>
And if you need to remove those same columns, you can generate a migration with the following :
script/generate migration RemoveTitleEmailFromUsers title:string email:string
The title of the migration is significant. The beginning Add/Remove specifies the action to take, the To/From specifies the tablename to apply the action against.
How sweet is that?!?
5 Comments »