问题描述
我错误地将列命名为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".
有关更多信息,请参见"活动记录迁移".
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:
在创建用于重命名列的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
这篇关于如何在Ruby on Rails迁移中重命名数据库列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!