views:

59

answers:

3

Hello. Is it possible to rename a column using a command like:

script/generate migration AddColumnToTable column:type

? Thanks.

+1  A: 

Great question. The answer is, unfortunately, no. See Rails 2.3.5 source code:

lib/rails_generator/generators/components/migration/migration_generator.rb

The only keywords that are recognized by the migration generator are add, remove, and to/from.

Alex Reisner
+2  A: 

Rails does have a migration command on the ActiveRecord ConnectionAdapter called rename_column. You can generate a migration and then write the code yourself. example (MySQL):

script/generate migration rename_my_column_by_hand

Then edit the file it creates:

class RenameMyColumnByHand < ActiveRecord::Migration
  def self.up
    rename_column :my_table, :old_name, :new_name
  end

  def self.down
    rename_column :my_table, :new_name, :old_name
  end
end

It executes SQL like:

ALTER TABLE my_table CHANGE old_name new_name BIGINT;

Note This only renames the column, it won't rename any references you have to it on other tables.

ScottD
Thank you Scott, very usefu
Victor P
A: 

I use a bit of trickery here. Say I want to change column foo to bar.

Create a migration with the following steps

  • Add a temporary column temp_foo
  • Update all records, saving foo's value in temp_foo
  • Add a bar column
  • Update all records, saving temp_foo's value in bar
  • Drop column foo
  • Drop column temp_foo

This is ex-tre-me-ly brittle. If one step fails, you might loose data..

bartzon