Victor
Victor

Reputation: 23922

renaming a column in Rails

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

script/generate migration AddColumnToTable column:type

? Thanks.

Upvotes: 9

Views: 8010

Answers (3)

bartzon
bartzon

Reputation: 46

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..

Upvotes: 2

scottd
scottd

Reputation: 7474

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.

Upvotes: 17

Alex Reisner
Alex Reisner

Reputation: 29427

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.

Upvotes: 2

Related Questions