微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用 PostgreSQL 和 Rails 4 自动生成 UUID

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

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

1 classCreateUuidPsqlExtension < ActiveRecord::Migration
2 defself.up
3 execute"CREATE EXTENSION \"uuid-ossp\";"
4
end
5
6 .down
7 "DROP EXTENSION \"uuid-ossp\";"
8 9 end

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

create_table:translations,id::uuiddo|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来进行替换。那么,你可以另起一列来放置它:

AddUuidToModelsThatNeedIt < ActiveRecord::Migration
defup
add_columnNowrap; margin:0px!important; padding:0px!important; border:0px!important; outline:0px!important; float:none!important; vertical-align:baseline!important; position:static!important; left:auto!important; top:auto!important; right:auto!important; bottom:auto!important; height:auto!important; width:auto!important; line-height:1.1em!important; font-family:Consolas,:uuid:uuid
down
remove_column:invoicesend

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

:default=>"uuid_generate_v4()"
end

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐