使用Ruby on Rails和PostgreSQL自动生成UUID的教程_ruby专题教程-查字典教程网
使用Ruby on Rails和PostgreSQL自动生成UUID的教程
使用Ruby on Rails和PostgreSQL自动生成UUID的教程
发布时间:2016-12-28 来源:查字典编辑
摘要:Rails4能原生态的支持Postgres中的UUID(UniversallyUniqueIdentifier,可通用的唯一标识符)类型。在...

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 看到更多有关这些算法的细节。

然而,有时候你不想用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能被自动创建了。同理也适用于已有记录!

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新ruby专题学习
    热门ruby专题学习
    脚本专栏子分类