我错误地将列命名为hased_password而不是hashed_password。

如何使用迁移重命名此列来更新数据库架构?


当前回答

首先你需要跑步

rails g migration create_new_column_in_tablename new_column:datatype
rails g migration remove_column_in_tablename old_column:datatype

然后需要检查db/migration您可以检查nem迁移中的详细信息,如果所有详细信息都正确,则需要运行:

rails db:migrate

其他回答

只需创建一个新的迁移,并在一个块中使用rename_column,如下所示。

rename_column :your_table_name, :hased_password, :hashed_password

生成RubyonRails迁移:

$:> rails g migration Fixcolumnname

在迁移文件中插入代码(XXXXX fixcolumnname.rb):

class Fixcolumnname < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

这可能比重命名列、创建新列并复制内容更好:

通过这种方式,我们可以保存旧列中的内容

这可能是一代人:

rails generate migration add_birthdate_to_User birthdate:string

这可能是迁移:

class AddBirthdateToUser < ActiveRecord::Migration[7.0]
  def change
    add_column :user, :birthdate, :json, default: '[]', null: false

    reversible do |dir|
      dir.up do
        User.update_all('birthdate=birtdate') # rubocop:disable Rails/SkipsModelValidations
      end
    end
  end
end

之后,您必须删除错误的“出生日期”列

class RemoveBirthdateFromUser < ActiveRecord::Migration[7.0]
  def change
    remove_column :User, :Birtdate, :json
  end
end

我在使用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

注意:在调用列名的所有位置,努力将列名修改为新名称。

若您的代码并没有和其他代码共享,那个么最好的选择就是只执行rakedb:rollback然后在migration和rakedb:migrate中编辑列名。就是这样

您可以编写另一个迁移来重命名列

 def change
    rename_column :table_name, :old_name, :new_name
  end

就是这样。