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

查看:59
本文介绍了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天全站免登陆