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

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


当前回答

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

rename_column :your_table_name, :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

如果当前数据对您不重要,您可以使用以下方法删除原始迁移:

rake db:migrate:down VERSION='YOUR MIGRATION FILE VERSION HERE'

如果没有引号,请在原始迁移中进行更改,然后通过以下方式再次运行升级迁移:

rake db:migrate
$:  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

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

rename_column(table_name, column_name, new_column_name):

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

如果需要切换列名,则需要创建占位符以避免出现“重复列名”错误。下面是一个示例:

class SwitchColumns < ActiveRecord::Migration
  def change
    rename_column :column_name, :x, :holder
    rename_column :column_name, :y, :x
    rename_column :column_name, :holder, :y
  end
end