我错误地将列命名为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

其他回答

RubyonRails的某些版本支持向上/向下迁移方法,如果您的迁移中有向上/下方法,那么:

def up
    rename_column :table_name, :column_old_name, :column_new_name
end

def down
    rename_column :table_name, :column_new_name, :column_old_name
end

如果您在迁移中使用了更改方法,那么:

def change
    rename_column :table_name, :column_old_name, :column_new_name
end

有关更多信息,请参阅:RubyonRails-迁移或活动记录迁移。

生成迁移文件:

rails g migration FixName

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

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

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

create_table的近亲是change_table,用于更改现有表。它以与create_table类似的方式使用,但向块提供的对象知道更多技巧。例如:

class ChangeBadColumnNames < ActiveRecord::Migration
  def change
    change_table :your_table_name do |t|
      t.rename :old_column_name, :new_column_name
    end
  end
end

如果我们将其与其他alter方法一起使用,例如:remove/add index/remove index/add column,则这种方法更有效。我们可以做以下事情:

重命名

t.rename :old_column_name, :new_column_name

添加列

t.string :new_column

删除列

t.remove :removing_column

索引列

t.index :indexing_column

rails g迁移migrationName

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

rename_column :table, :old_column, :new_column

到方法

在我看来,在这种情况下,最好使用rakedb:rollback,然后编辑迁移并再次运行rakedb:migrate。

但是,如果列中有不希望丢失的数据,请使用rename_column。