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

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


当前回答

在我看来,在这种情况下,最好使用rakedb:rollback,然后编辑迁移并再次运行rakedb:migrate。

但是,如果列中有不希望丢失的数据,请使用rename_column。

其他回答

rails g迁移migrationName

因此,您转到生成的迁移并添加:

rename_column :table, :old_column, :new_column

到方法

对于Ruby on Rails 4:

def change
    rename_column :table_name, :column_name_old, :column_name_new
end
$:  rails g migration RenameHashedPasswordColumn
invoke  active_record
      create    db/migrate/20160323054656_rename_hashed_password_column.rb

打开该迁移文件并按如下方式修改该文件(请输入原始table_name)

class  RenameHashedPasswordColumn < 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

只需使用以下方法生成迁移:

rails g migration rename_hased_password

之后,编辑迁移并在更改方法中添加以下行:

rename_column :table, :hased_password, :hashed_password

这应该会奏效。