当前位置: 移动技术网 > IT编程>脚本编程>Ruby > 使用Ruby on Rails和PostgreSQL自动生成UUID的教程

使用Ruby on Rails和PostgreSQL自动生成UUID的教程

2017年12月08日  | 移动技术网IT编程  | 我要评论
rails 4 能原生态的支持postgres 中的uuid(universally unique identifier,可通用的唯一标识符)类型。在此,我将向你描述如何在

rails 4 能原生态的支持 中的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能被自动创建了。同理也适用于已有记录!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网