rename_column :table, :old_column, :new_column
Update:
(更新:)
You'll probably want to create a separate migration to do this.
(您可能希望创建单独的迁移来执行此操作。)
(Rename FixColumnName as you will) ((按照您的意愿重命名FixColumnName))
script/generate migration FixColumnName
# creates db/migrate/xxxxxxxxxx_fix_column_name.rb
Then edit the migration to do your will.
(然后编辑迁移以执行您的意愿。)
# db/migrate/xxxxxxxxxx_fix_column_name.rb
class FixColumnName < ActiveRecord::Migration
def self.up
rename_column :table_name, :old_column, :new_column
end
def self.down
# rename back if you need or do something else or do nothing
end
end
An update for Rails 3.1
(Rails 3.1的更新)
While, the up
and down
methods still apply.
(同时,在up
和down
的方法仍然适用。)
Rails 3.1 receives a change
method that "knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method" (Rails 3.1接收一个change
方法, “知道如何迁移数据库并在回滚迁移时将其反转,而无需编写单独的down方法”)
rails g migration FixColumnName
class FixColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again.
(如果您碰巧有一大堆要重命名的列,或者需要一遍又一遍地重复表名的内容。)
rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...
You could use change_table
to keep things a little neater.
(你可以使用change_table
来保持一点整洁。)
class FixColumnNames < ActiveRecord::Migration
def change
change_table :table_name do |t|
t.rename :old_column1, :new_column1
t.rename :old_column2, :new_column2
...
end
end
end
Thank you, Luke
&& Turadg
, for bringing up the topic.
(感谢Luke
&& Turadg
提出这个话题。)
Then just db:migrate
as usual or however you go about your business.
(然后只是db:migrate
像往常一样db:migrate
,或者你继续开展业务。)
An update for Rails 4
(Rails 4的更新)
While creating a Migration
as for renaming a column, Rails 4 generates a change
method instead of up
and down
as mentioned in the above answer.
(在创建Migration
作为用于重命名的列,轨道4产生change
的方法,而不是up
和down
如在上面提到的答案。)
The generated change
method is as below : (生成的change
方法如下:)
$ > rails g migration ChangeColumnName
which will create a migration file similar to this :
(这将创建一个类似于此的迁移文件:)
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end