我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
当前回答
若您的代码并没有和其他代码共享,那个么最好的选择就是只执行rakedb:rollback然后在migration和rakedb:migrate中编辑列名。就是这样
您可以编写另一个迁移来重命名列
def change
rename_column :table_name, :old_name, :new_name
end
就是这样。
其他回答
我们可以手动使用以下方法:
我们可以手动编辑迁移,如:
打开app/db/migrate/xxxxx_migration_file.rb将hased_password更新为hashed_passwords运行以下命令$>rakedb:migrate:down VERSION=xxxxxxxxx
然后它将删除您的迁移:
$> rake db:migrate:up VERSION=xxxxxxxxx
它将使用更新的更改添加您的迁移。
Rails 5迁移更改
eg:
rails g model学生Student_name:字符串年龄:整数
如果要将student_name列更改为name
注意:-如果没有运行railsdb:migrate
您可以执行以下步骤
rails d model学生Student_name:字符串年龄:整数
这将删除生成的迁移文件,现在您可以更正列名
rails g model学生姓名:string年龄:整数
如果已迁移(railsdb:migrate),请使用以下选项更改列名
rails g迁移RemoveStudentNameFromStudent student_name:字符串rails g迁移AddNameToStudent名称:字符串
您可以编写迁移,运行以下命令以更新列名:
rename_column :your_table_name, :hased_password, :hashed_password
此外,确保用新列名更新代码中旧列名的任何用法。
这可能比重命名列、创建新列并复制内容更好:
通过这种方式,我们可以保存旧列中的内容
这可能是一代人:
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
打开RubyonRails控制台并输入:
ActiveRecord::Migration.rename_column :tablename, :old_column, :new_column