Rails 4. 将表 id 迁移到 UUID [英] Rails 4. Migrate table id to UUID

查看:18
本文介绍了Rails 4. 将表 id 迁移到 UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子:db/migrate/20140731201801_create_voc_brands.rb:

class CreateVocBrands < ActiveRecord::Migration
  def change
    create_table :voc_brands do |t|
      t.string :name

      t.timestamps
    end
  end
end

但我需要将表更改为这个(如果我要从零开始创建它):

But I need to change table to this(if I would create it from zero):

class CreateVocBrands < ActiveRecord::Migration
  def change
    create_table :voc_brands, :id => false do |t|
      t.uuid :id, :primary_key => true
      t.string :name

      t.timestamps
    end
    add_index :voc_brands, :id
  end
end

如何使用迁移来更改此设置?

How can I change this using migration?

推荐答案

我遇到了和你一样的问题.要从默认 id 迁移到使用 uuid,我认为您可以使用类似于我所拥有的东西:

I had the same problem as yours. To migrate from default id to use uuid, I think you could something similar to what I had:

class ChangeVocBrandsPrimaryKey < ActiveRecord::Migration
  def change
    add_column :voc_brands, :uuid, :uuid, default: "uuid_generate_v4()", null: false

    change_table :voc_brands do |t|
      t.remove :id
      t.rename :uuid, :id
    end
    execute "ALTER TABLE voc_brands ADD PRIMARY KEY (id);"
  end
end

这篇关于Rails 4. 将表 id 迁移到 UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆