我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
当前回答
对于Ruby on Rails 4:
def change
rename_column :table_name, :column_name_old, :column_name_new
end
其他回答
运行以下命令以创建迁移文件:
rails g migration ChangeHasedPasswordToHashedPassword
然后在db/migrate文件夹中生成的文件中,按如下方式写入rename_column:
class ChangeOldColumnToNewColumn < ActiveRecord::Migration
def change
rename_column :table_name, :hased_password, :hashed_password
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 generate migration newMigration
在newMigration文件中:
class FixColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
打开RubyonRails控制台并输入:
ActiveRecord::Migration.rename_column :tablename, :old_column, :new_column
只需创建一个新的迁移,并在一个块中使用rename_column,如下所示。
rename_column :your_table_name, :hased_password, :hashed_password