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

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


当前回答

我在rails 5.2上,试图重命名device User上的列。

rename_column位对我有效,但单数:table_name抛出了“User table not found”错误。Plural为我工作。

rails g RenameAgentinUser

然后将迁移文件更改为:

rename_column :users, :agent?, :agent

哪里:代理人?是旧的列名。

其他回答

从API:

rename_column(table_name, column_name, new_column_name)

这将重命名列,但保持类型和内容不变。

打开RubyonRails控制台并输入:

ActiveRecord::Migration.rename_column :tablename, :old_column, :new_column

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

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

这可能是一代人:

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

对于Ruby on Rails 4:

def change
    rename_column :table_name, :column_name_old, :column_name_new
end