Modifying An Existing Table

Add fields to an existing table

shell$ script/generate migration AddAddressToPoliticians

codetitle. db/migrations/002_add_address_to_politicians.rb

class AddAddressToPoliticians < ActiveRecord::Migration
  def self.up
    add_column :politicians, :address, :string

  end

  def self.down
    remove_column :politicians, :address

  end
end
shell$ rake db:migrate

the available column types are: boolean, integer, float, string, text, datetime, blob

Changing the default values

change_column(table_name, column_name, type, options)

When you need to execute raw SQL

Sometimes you need to execute raw SQL in your migration. In general, this should be avoided when possible, because may lock your application to a specific database.

class AlterWatchInUserParticipations < ActiveRecord::Migration
  def self.up
    execute "ALTER TABLE `user_participations` ALTER COLUMN `watch` SET DEFAULT FALSE"
  end

  def self.down
    execute "ALTER TABLE `user_participations` ALTER COLUMN `watch` DROP DEFAULT"
  end
end