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

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


当前回答

 def change
    rename_column :table_name, :old_column_name, :new_column_name
  end

其他回答

首先你需要跑步

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

作为另一种选择,如果您不喜欢迁移,ActiveRecord有一个引人注目的优点,它将自动为您处理名称更改,Datamapper风格。您只需更改模型中的列名,并确保将model.auto_upgrade!在model.rb和viola的底部!数据库随时更新。

看见https://github.com/DAddYE/mini_record

注意:您需要nuke db/schema.rb来防止冲突。

它仍然处于测试阶段,显然不适合所有人,但它仍然是一个令人信服的选择。我目前在两个非平凡的生产应用程序中使用它,没有任何问题。

您可以编写迁移,运行以下命令以更新列名:

rename_column :your_table_name, :hased_password, :hashed_password

此外,确保用新列名更新代码中旧列名的任何用法。

运行以下命令以创建迁移文件:

rails g migration ChangeHasedPasswordToHashedPassword

然后在db/migrate文件夹中生成的文件中,按如下方式写入rename_column:

class ChangeOldColumnToNewColumn < ActiveRecord::Migration
  def change
     rename_column :table_name, :hased_password, :hashed_password
  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