【发布时间】:2021-10-16 04:35:16
【问题描述】:
我目前正在编写代码以将我们的数据库默认 ID 列转换为 UUID 格式。
我的迁移代码示例是
def up
remove_reference :examples, :user, null: false, foreign_key: true
add_column :users, :uuid, :uuid, default: "gen_random_uuid()", null: false
change_table :users do |t|
t.remove :id, type: :id
t.rename :uuid, :id
end
execute "ALTER TABLE users ADD PRIMARY KEY (id);"
add_reference :examples, :user, null: false, foreign_key: true, type: :uuid
end
基本上这允许我将我的 ID 列转换为 UUID 格式。
我创建了一个向下函数,以便能够回滚,但由于此错误而失败 ERROR: column "user_id" of relationship "examples" contains null values
我意识到会有一个问题,因为一旦数据库中有数据,它将无法回滚并再次创建正确的引用。有人对我应该如何处理我的向下功能有任何想法吗?
def down
remove_reference :examples, :user, null: false, foreign_key: true, type: :uuid
execute 'ALTER TABLE users DROP CONSTRAINT users_pkey'
add_column :users, :new_id, :primary_key
change_table :users do |t|
t.remove :id, type: :uuid
t.rename :new_id, :id
end
add_reference :examples, :user, null: false, foreign_key: true
end
有人对我应该如何进行此操作有任何建议吗?原来的迁移是在一个变更函数中,但由于执行块而无法回滚。
【问题讨论】:
标签: ruby-on-rails postgresql rails-activerecord