Tuesday, June 14, 2011

Change a column data type with Rails migration

I always forget the syntax for this and I have to look it up, so I am going to post it here. Maybe this will help some others out. Basically, what I need to do is change the data type of a column in my database table. The table “address” contains a column/field named “postal_code” which was integer type. I want to change postal_code from an integer to a string. So first I create a rails migration with the following command.

class AlterPostalCodeToString < ActiveRecord::Migration
def self.up
change_table :addresses do |address|
address.change :postal_code, :string
end
change_table :company_addresses do |address|
address.change :postal_code, :string
end
end

def self.down
change_table :addresses do |address|
address.change :postal_code, :integer
end
change_table :company_addresses do |address|
address.change :postal_code, :integer
end
end
end

No comments:

Post a Comment