我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
我错误地将列命名为hased_password而不是hashed_password。
如何使用迁移重命名此列来更新数据库架构?
当前回答
如果该列中已经填充了数据并在生产环境中运行,我建议采用一步一步的方法,以便在等待迁移时避免生产环境中的停机。
首先,我将创建一个数据库迁移,以添加具有新名称的列,并用旧列名的值填充它们。
class AddCorrectColumnNames < ActiveRecord::Migration
def up
add_column :table, :correct_name_column_one, :string
add_column :table, :correct_name_column_two, :string
puts 'Updating correctly named columns'
execute "UPDATE table_name SET correct_name_column_one = old_name_column_one, correct_name_column_two = old_name_column_two"
end
end
def down
remove_column :table, :correct_name_column_one
remove_column :table, :correct_name_column_two
end
end
然后我会做出改变,并将其付诸生产。
git commit -m 'adding columns with correct name'
然后,一旦提交被推到生产中,我就会运行。
Production $ bundle exec rake db:migrate
然后,我会将引用旧列名的所有视图/控制器更新为新列名。运行我的测试套件,并提交这些更改。(确保它在本地工作并首先通过所有测试后!)
git commit -m 'using correct column name instead of old stinky bad column name'
然后我会把这个承诺推向生产。
此时,您可以删除原始列,而不必担心与迁移本身相关的任何停机时间。
class RemoveBadColumnNames < ActiveRecord::Migration
def up
remove_column :table, :old_name_column_one
remove_column :table, :old_name_column_two
end
def down
add_column :table, :old_name_column_one, :string
add_column :table, :old_name_column_two, :string
end
end
然后将最新的迁移推送到生产环境,并在后台运行bundle exec rake db:migrate。
我意识到这是一个更复杂的过程,但我宁愿这样做,也不想在生产迁移中遇到问题。
其他回答
这可能比重命名列、创建新列并复制内容更好:
通过这种方式,我们可以保存旧列中的内容
这可能是一代人:
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
rails g迁移migrationName
因此,您转到生成的迁移并添加:
rename_column :table, :old_column, :new_column
到方法
打开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 g migration ChangesNameInUsers(或任何您想命名的名称)
打开刚刚生成的迁移文件,并在方法中添加此行(在def change和end之间):
重命名列:表名,:名称you_want_to_change,:新名称
保存文件,并在控制台中运行rakedb:migrate
检查你的schema.db,看看数据库中的名称是否真的改变了!
希望这有帮助:)