加载中

Rails 4 has native support for the type UUID (Universally Unique Identifier) in Postgres. In this Div Bit I will describe how you can use it for generating UUIDs without doing it manually in your Rails code.

First you need to enable the Postgres extension ‘uuid-ossp’:

class CreateUuidPsqlExtension < ActiveRecord::Migration
  def self.up
    execute "CREATE EXTENSION \"uuid-ossp\";"
  end

  def self.down
    execute "DROP EXTENSION \"uuid-ossp\";"
  end
end

You can use a UUID as a ID replacement:

create_table :translations, id: :uuid do |t|
  t.string :title
  t.timestamps
end

In this case the Translations table will have a UUID as ID and it is autogenerated. The uuid-ossp extension in Postgresq has different algorithms how the UUID is generated. Rails 4 uses v4 per default. You can read more about these algorithms here: http://www.postgresql.org/docs/current/static/uuid-ossp.html

Rails 4 能原生态的支持Postgres 中的UUID(Universally Unique Identifier,可通用的唯一标识符)类型。在此,我将向你描述如何在不用手工修改任何Rails代码的情况下,用它来生成UUID。

首先,你需要激活Postgres的扩展插件‘uuid-ossp’:

class CreateUuidPsqlExtension < ActiveRecord::Migration
  def self.up
    execute "CREATE EXTENSION \"uuid-ossp\";"
  end

  def self.down
    execute "DROP EXTENSION \"uuid-ossp\";"
  end
end

你可以用UUID作为一个ID来进行替换:

create_table :translations, id: :uuid do |t|
  t.string :title
  t.timestamps
end

在此例中,翻译表会把一个UUID作为ID来自动生成它。Postgresq的uuid-ossp扩展插件所用算法和生成UUID的算法是不同的。Rails 4缺省使用的是v4算法. 你可以在这里: http://www.postgresql.org/docs/current/static/uuid-ossp.html 看到更多有关这些算法的细节。

However, sometimes you don't want to have the UUID as ID replacement and instead have it in a separate column:

class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
  def up
    add_column :translations, :uuid, :uuid
  end

  def down
    remove_column :invoices, :uuid
  end
end

This will create a UUID column, but the UUID will not be autogenerated. You have to do it yourself in Rails with SecureRandom. However, we think that this is a typical database responsibility. Fortunately, the default option in add_column helps:

class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
  def up
    add_column :translations, :uuid, :uuid, :default => "uuid_generate_v4()"
  end

  def down
    remove_column :invoices, :uuid
  end
end

Now the UUID will be created automatically, also for existing records!

然而,有时候你不想用UUID作为ID来进行替换。那么,你可以另起一列来放置它:

class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
  def up
    add_column :translations, :uuid, :uuid
  end

  def down
    remove_column :invoices, :uuid
  end
end

这会创建一个放置UUID的列,但这个UUID不会自动生成。你不得不在Rails中用SecureRandom来生成它。但是,我们认为这是一个典型的数据库职责行为。值得庆幸的是,add_column中的缺省选项会帮我们实现这种行为:

class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
  def up
    add_column :translations, :uuid, :uuid, :default => "uuid_generate_v4()"
  end

  def down
    remove_column :invoices, :uuid
  end
end

现在,UUID能被自动创建了。同理也适用于已有记录!

返回顶部
顶部