我错误地将列命名为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)
这将重命名列,但保持类型和内容不变。
我在使用PostgreSQL数据库开发Rails 6应用程序时遇到了这个挑战。
以下是我修复它的方法:
在我的例子中,table_name是“Products”,old_column是“SKU”,new_column则是“ProductNumber”。
创建包含用于重命名列的命令的迁移文件:rails生成迁移重命名KUToProductNumberInProducts打开db/migrate目录中的迁移文件:数据库/migrate/2021028082344_rename_sku_to_product_number_in_products.rb添加用于重命名列的命令:类RenameKuToProductNumberInProducts<ActiveRecord::迁移[6.0]def更改#重命名列:表名,:旧列,:新列重命名列:产品,:sku,:product_number终止终止保存,然后运行迁移命令:轨道数据库:移植
现在,您可以通过查看架构文件来确认列的重命名:
db/schema.rb
如果您对列的重命名不满意,可以始终回滚:
rails db:rollback
注意:在调用列名的所有位置,努力将列名修改为新名称。
rails g迁移migrationName
因此,您转到生成的迁移并添加:
rename_column :table, :old_column, :new_column
到方法
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
def change
rename_column :table_name, :old_column_name, :new_column_name
end