我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
当前回答
只需使用以下方法生成迁移:
rails g migration rename_hased_password
之后,编辑迁移并在更改方法中添加以下行:
rename_column :table, :hased_password, :hashed_password
这应该会奏效。
其他回答
如果需要切换列名,则需要创建占位符以避免出现“重复列名”错误。下面是一个示例:
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
在控制台中:
rails generate migration newMigration
在newMigration文件中:
class FixColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
这可能比重命名列、创建新列并复制内容更好:
通过这种方式,我们可以保存旧列中的内容
这可能是一代人:
rails generate migration add_birthdate_to_User birthdate:string
这可能是迁移:
class AddBirthdateToUser < ActiveRecord::Migration[7.0]
def change
add_column :user, :birthdate, :json, default: '[]', null: false
reversible do |dir|
dir.up do
User.update_all('birthdate=birtdate') # rubocop:disable Rails/SkipsModelValidations
end
end
end
end
之后,您必须删除错误的“出生日期”列
class RemoveBirthdateFromUser < ActiveRecord::Migration[7.0]
def change
remove_column :User, :Birtdate, :json
end
end
rename_column :table, :old_column, :new_column
您可能需要创建一个单独的迁移来实现这一点。(根据需要重命名FixColumnName。):
bin/rails generate migration FixColumnName
# creates db/migrate/xxxxxxxxxx_fix_column_name.rb
然后编辑迁移以执行您的意愿:
# db/migrate/xxxxxxxxxx_fix_column_name.rb
class FixColumnName < ActiveRecord::Migration
def self.up
rename_column :table_name, :old_column, :new_column
end
def self.down
# rename back if you need or do something else or do nothing
end
end
对于Rails 3.1,请使用:
尽管向上和向下方法仍然适用,但Rails3.1收到了一个更改方法,该方法“知道如何迁移数据库,并在回滚迁移时反转数据库,而无需编写单独的向下方法”。
有关详细信息,请参阅“活动记录迁移”。
rails g migration FixColumnName
class FixColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
如果您恰好有一大堆列要重命名,或者需要反复重复表名:
rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...
您可以使用change_table使事情变得更整洁:
class FixColumnNames < ActiveRecord::Migration
def change
change_table :table_name do |t|
t.rename :old_column1, :new_column1
t.rename :old_column2, :new_column2
...
end
end
end
然后只需要db:像往常一样迁移,或者不管你怎么做。
对于轨道4:
在创建用于重命名列的Migration时,Rails4生成了一个更改方法,而不是上一节中提到的上下更改方法。生成的更改方法为:
$ > rails g migration ChangeColumnName
这将创建类似于以下内容的迁移文件:
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
作为另一种选择,如果您不喜欢迁移,ActiveRecord有一个引人注目的优点,它将自动为您处理名称更改,Datamapper风格。您只需更改模型中的列名,并确保将model.auto_upgrade!在model.rb和viola的底部!数据库随时更新。
看见https://github.com/DAddYE/mini_record
注意:您需要nuke db/schema.rb来防止冲突。
它仍然处于测试阶段,显然不适合所有人,但它仍然是一个令人信服的选择。我目前在两个非平凡的生产应用程序中使用它,没有任何问题。