Reputation: 23922
Is it possible to rename a column using a command like:
script/generate migration AddColumnToTable column:type
? Thanks.
Upvotes: 9
Views: 8010
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
This is ex-tre-me-ly brittle. If one step fails, you might loose data..
Upvotes: 2
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
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