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

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


当前回答

生成RubyonRails迁移:

$:> rails g migration Fixcolumnname

在迁移文件中插入代码(XXXXX fixcolumnname.rb):

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

其他回答

如果该列中已经填充了数据并在生产环境中运行,我建议采用一步一步的方法,以便在等待迁移时避免生产环境中的停机。

首先,我将创建一个数据库迁移,以添加具有新名称的列,并用旧列名的值填充它们。

class AddCorrectColumnNames < ActiveRecord::Migration
  def up
    add_column :table, :correct_name_column_one, :string
    add_column :table, :correct_name_column_two, :string

    puts 'Updating correctly named columns'
    execute "UPDATE table_name SET correct_name_column_one = old_name_column_one, correct_name_column_two = old_name_column_two"
    end
  end

  def down
    remove_column :table, :correct_name_column_one
    remove_column :table, :correct_name_column_two
  end
end

然后我会做出改变,并将其付诸生产。

git commit -m 'adding columns with correct name'

然后,一旦提交被推到生产中,我就会运行。

Production $ bundle exec rake db:migrate

然后,我会将引用旧列名的所有视图/控制器更新为新列名。运行我的测试套件,并提交这些更改。(确保它在本地工作并首先通过所有测试后!)

git commit -m 'using correct column name instead of old stinky bad column name'

然后我会把这个承诺推向生产。

此时,您可以删除原始列,而不必担心与迁移本身相关的任何停机时间。

class RemoveBadColumnNames < ActiveRecord::Migration
  def up
    remove_column :table, :old_name_column_one
    remove_column :table, :old_name_column_two
  end

  def down
    add_column :table, :old_name_column_one, :string
    add_column :table, :old_name_column_two, :string
  end
end

然后将最新的迁移推送到生产环境,并在后台运行bundle exec rake db:migrate。

我意识到这是一个更复杂的过程,但我宁愿这样做,也不想在生产迁移中遇到问题。

打开RubyonRails控制台并输入:

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

Rails 5迁移更改

eg:

rails g model学生Student_name:字符串年龄:整数

如果要将student_name列更改为name

注意:-如果没有运行railsdb:migrate

您可以执行以下步骤

rails d model学生Student_name:字符串年龄:整数

这将删除生成的迁移文件,现在您可以更正列名

rails g model学生姓名:string年龄:整数

如果已迁移(railsdb:migrate),请使用以下选项更改列名

rails g迁移RemoveStudentNameFromStudent student_name:字符串rails g迁移AddNameToStudent名称:字符串

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

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

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

然后它将删除您的迁移:

$> rake db:migrate:up VERSION=xxxxxxxxx

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

作为另一种选择,如果您不喜欢迁移,ActiveRecord有一个引人注目的优点,它将自动为您处理名称更改,Datamapper风格。您只需更改模型中的列名,并确保将model.auto_upgrade!在model.rb和viola的底部!数据库随时更新。

看见https://github.com/DAddYE/mini_record

注意:您需要nuke db/schema.rb来防止冲突。

它仍然处于测试阶段,显然不适合所有人,但它仍然是一个令人信服的选择。我目前在两个非平凡的生产应用程序中使用它,没有任何问题。