Notes on Rails migrations

Migrations are used to specify changes to the database schema, like adding a new column or table. The first step is to ask Rails to create a new migration:

rails generate migration name-of-migration

This will cause Rails to create a stub migration file that starts with a date-and-time stamp and ends with the name you specified. This file will be in db/migrate. For example:

20120324013120_director.rb

Now you edit this file to tell it how to change the schema, and undo the changes, in the up and down methods of the class named after the name of your migration.

The kind of things you can put here are documented in ActiveRecord Migrations, but typically involve create a table, or adding columns to an existing table. (And removing them in the down method.)

add_column :mytable, :mycolumn, :string

remove_column :mytable, :mycolumn

Note: The type :string is used for things that are relatively short, like usernames, title of articles etc. The type :text is for long pieces of text, like the contents of an article. Typically the database implementation might allows as much as gigabytes of text in a field of the :text type. (ref)

After defining a migration you must apply it to the development and test versions of your database, like so:

rake db:migrate
rake db:test:prepare

About these ads
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s