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

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


当前回答

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

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

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

然后它将删除您的迁移:

$> rake db:migrate:up VERSION=xxxxxxxxx

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

其他回答

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

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

rename_column(table_name, column_name, new_column_name):

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

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 rename_hased_password

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

rename_column :table, :hased_password, :hashed_password

这应该会奏效。

您有两种方法可以做到这一点:

在这种类型中,当回滚时,它会自动运行与其相反的代码。def更改重命名列:表名称,:旧列名称,:新列名称终止对于这种类型,它在rakedb:migrate时运行up方法,在rakedb:rollback时运行down方法:定义self.up重命名列:表名称,:旧列名称,:新列名称终止定义自己向下重命名列:表名称,:新列名称,:旧列名称终止