我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
当前回答
首先你需要跑步
rails g migration create_new_column_in_tablename new_column:datatype
rails g migration remove_column_in_tablename old_column:datatype
然后需要检查db/migration您可以检查nem迁移中的详细信息,如果所有详细信息都正确,则需要运行:
rails db:migrate
其他回答
您有两种方法可以做到这一点:
在这种类型中,当回滚时,它会自动运行与其相反的代码。def更改重命名列:表名称,:旧列名称,:新列名称终止对于这种类型,它在rakedb:migrate时运行up方法,在rakedb:rollback时运行down方法:定义self.up重命名列:表名称,:旧列名称,:新列名称终止定义自己向下重命名列:表名称,:新列名称,:旧列名称终止
在我看来,在这种情况下,最好使用rakedb:rollback,然后编辑迁移并再次运行rakedb:migrate。
但是,如果列中有不希望丢失的数据,请使用rename_column。
生成RubyonRails迁移:
$:> rails g migration Fixcolumnname
在迁移文件中插入代码(XXXXX fixcolumnname.rb):
class Fixcolumnname < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
def change
rename_column :table_name, :old_column_name, :new_column_name
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