问题描述
我错误地将列命名为 hased_password
而不是 hashed_password
.
I wrongly named a column hased_password
instead of hashed_password
.
如何更新数据库架构,使用迁移重命名此列?
How do I update the database schema, using migration to rename this column?
推荐答案
rename_column :table, :old_column, :new_column
您可能需要创建一个单独的迁移来执行此操作.(根据需要重命名 FixColumnName
.):
You'll probably want to create a separate migration to do this. (Rename FixColumnName
as you will.):
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
对于 Rails 3.1 使用:
For Rails 3.1 use:
虽然 up
和 down
方法仍然适用,但 Rails 3.1 收到了一个 change
方法,该方法知道如何迁移数据库并反向当迁移回滚时,无需编写单独的向下方法".
While, the up
and down
methods still apply, 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".
有关详细信息,请参阅Active Record 迁移".
See "Active Record Migrations" for more information.
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
...
您可以使用 change_table
使事情更整洁:
You could use change_table
to keep things a little neater:
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
然后像往常一样db:migrate
,或者按照您的业务进行.
Then just db:migrate
as usual or however you go about your business.
对于 Rails 4:
For Rails 4:
在创建用于重命名列的 Migration
时,Rails 4 生成一个 change
方法而不是 up
和 down
> 如上一节所述.生成的change
方法为:
While creating a Migration
for renaming a column, Rails 4 generates a change
method instead of up
and down
as mentioned in the above section. The generated change
method is:
$ > rails g migration ChangeColumnName
这将创建一个类似于以下内容的迁移文件:
which will create a migration file similar to:
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
这篇关于Rails:如何在 Ruby on Rails 迁移中重命名数据库列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!