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

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


当前回答

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

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

这可能是一代人:

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

其他回答

请参阅“活动记录迁移”文档中的“可用转换”部分。

rename_column(table_name, column_name, new_column_name):

重命名列,但保留类型和内容。

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

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 5.2。

1.创建迁移

rails g迁移重命名为FullNameInStudentsrails g RenameOldFieldToNewFieldInTableName-这样以后代码库的维护人员就非常清楚了(表名使用复数)。

2.编辑迁移

#我更喜欢显式地编写panddown方法。

# ./数据库/migrate/20190114045137_rename_name_to_full_name_in_students.rb

class RenameNameToFullNameInStudents < ActiveRecord::Migration[5.2]
  def up
    # rename_column :table_name, :old_column, :new_column
    rename_column :students, :name, :full_name
  end

  def down
            # Note that the columns are reversed
    rename_column :students, :full_name, :name
  end
end

3.运行迁移

rake数据库:迁移

你要去参加比赛了!

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

rails g migration rename_hased_password

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

rename_column :table, :hased_password, :hashed_password

这应该会奏效。

rails g迁移migrationName

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

rename_column :table, :old_column, :new_column

到方法