我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
当前回答
只需创建一个新的迁移,并在一个块中使用rename_column,如下所示。
rename_column :your_table_name, :hased_password, :hashed_password
其他回答
从API:
rename_column(table_name, column_name, new_column_name)
这将重命名列,但保持类型和内容不变。
让我们接吻。它只需要三个简单的步骤。以下适用于Rails 5.2。
1.创建迁移
rails g迁移重命名为FullNameInStudentsrails g RenameOldFieldToNewFieldInTableName-这样以后代码库的维护人员就非常清楚了(表名使用复数)。
2.编辑迁移
#我更喜欢显式地编写panddown方法。
# ./数据库/migrate/20190114045137_rename_name_to_full_name_in_students.rb
class RenameNameToFullNameInStudents < ActiveRecord::Migration[5.2]
def up
# rename_column :table_name, :old_column, :new_column
rename_column :students, :name, :full_name
end
def down
# Note that the columns are reversed
rename_column :students, :full_name, :name
end
end
3.运行迁移
rake数据库:迁移
你要去参加比赛了!
rename_column :table, :old_column, :new_column
您可能需要创建一个单独的迁移来实现这一点。(根据需要重命名FixColumnName。):
bin/rails generate migration FixColumnName
# creates db/migrate/xxxxxxxxxx_fix_column_name.rb
然后编辑迁移以执行您的意愿:
# 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,请使用:
尽管向上和向下方法仍然适用,但Rails3.1收到了一个更改方法,该方法“知道如何迁移数据库,并在回滚迁移时反转数据库,而无需编写单独的向下方法”。
有关详细信息,请参阅“活动记录迁移”。
rails g migration FixColumnName
class FixColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
如果您恰好有一大堆列要重命名,或者需要反复重复表名:
rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...
您可以使用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
然后只需要db:像往常一样迁移,或者不管你怎么做。
对于轨道4:
在创建用于重命名列的Migration时,Rails4生成了一个更改方法,而不是上一节中提到的上下更改方法。生成的更改方法为:
$ > rails g migration ChangeColumnName
这将创建类似于以下内容的迁移文件:
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
create_table的近亲是change_table,用于更改现有表。它以与create_table类似的方式使用,但向块提供的对象知道更多技巧。例如:
class ChangeBadColumnNames < ActiveRecord::Migration
def change
change_table :your_table_name do |t|
t.rename :old_column_name, :new_column_name
end
end
end
如果我们将其与其他alter方法一起使用,例如:remove/add index/remove index/add column,则这种方法更有效。我们可以做以下事情:
重命名
t.rename :old_column_name, :new_column_name
添加列
t.string :new_column
删除列
t.remove :removing_column
索引列
t.index :indexing_column
如果当前数据对您不重要,您可以使用以下方法删除原始迁移:
rake db:migrate:down VERSION='YOUR MIGRATION FILE VERSION HERE'
如果没有引号,请在原始迁移中进行更改,然后通过以下方式再次运行升级迁移:
rake db:migrate