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

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


当前回答

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 migration FixName

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

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

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

打开RubyonRails控制台并输入:

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

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 5.2上,试图重命名device User上的列。

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

rails g RenameAgentinUser

然后将迁移文件更改为:

rename_column :users, :agent?, :agent

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

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

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