Super Spread Sheet S³

Or little computing tricks and hacks

Migrations in Rails

One of the beauties of Rails is that you can make migrations at any time. You can modify whatever you want in your database: delete or add columns, change names, change data types.

The first step is to create a migration:

rails g migration add_user_id_to_articles user_id:integer

This creates a migration file (name given by the system)


and its content:

class AddUserIdToArticles < ActiveRecord::Migration
  def change
    add_column :articles, :user_id, :integer

This file can be modified before running the migration. It is a good idea to always check the file and make sure that it is doing what you want. When the system can predict the migration as in the example above, the change will be added to the migration file. The examples quoted in the guide are for adding or deleting attributes, provided that all the details are included (name and type of parameter). The example in the guide are

$ rails generate migration RemovePartNumberFromProducts part_number:string

which generates

class RemovePartNumberFromProducts < ActiveRecord::Migration
  def change
    remove_column :products, :part_number, :string

Some other times an empty migration is created. This is usually the case of a migration involving a change of name:

rails g migration change_name_to_other_in_events

which is equivalent to:

rails g migration ChangeNametoOtherInEvents

This migration will create the following file:

class ChangeWhenToWhenwhenInEvents < ActiveRecord::Migration
  def change

If you change your mind and do not want to perform the migration, change the rails g for generate, to rails d for delete.

In this case the migration needs to be filled in. As I want to change the name of the column, the missing code is:

    rename_column :events, :name, :other

If the change is of data type to text, the code is:

    change_column :events, :name, :text

More information on the types of migrations can be found at:

Once happy with the migration file, run the migration:

rake db:migrate

Do not forget to run

rake db:migrate RAILS_ENV=test

for the testing framework.

The migration with rollback is as follows:

class ChangeWhenFromTimeToDatetimeInEvent < ActiveRecord::Migration
  def up
    change_column :events, :when, :datetime
  def down
    change_column :events, :when, :time

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: