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

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


当前回答

生成迁移文件:

rails g migration FixName

这将创建db/migrate/xxxxxxxxxxx.rb。

编辑迁移以实现您的愿望:

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

其他回答

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

rails g migration ChangeHasedPasswordToHashedPassword

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

class ChangeOldColumnToNewColumn < ActiveRecord::Migration
  def change
     rename_column :table_name, :hased_password, :hashed_password
  end
end

对于Ruby on Rails 4:

def change
    rename_column :table_name, :column_name_old, :column_name_new
end
 def change
    rename_column :table_name, :old_column_name, :new_column_name
  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

我们可以手动使用以下方法:

我们可以手动编辑迁移,如:

打开app/db/migrate/xxxxx_migration_file.rb将hased_password更新为hashed_passwords运行以下命令$>rakedb:migrate:down VERSION=xxxxxxxxx

然后它将删除您的迁移:

$> rake db:migrate:up VERSION=xxxxxxxxx

它将使用更新的更改添加您的迁移。