Rails 4 能原生態(tài)的支持Postgres 中的UUID(Universally Unique Identifier,可通用的唯一標(biāo)識符)類型。在此,我將向你描述如何在不用手工修改任何Rails代碼的情況下,用它來生成UUID。
首先,你需要激活Postgres的擴(kuò)展插件‘uuid-ossp':
1
2
3
4
5
6
7
8
9
|
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來進(jìn)行替換:
1
2
3
4
|
create_table :translations , id: :uuid do |t| t.string :title t.timestamps end |
在此例中,翻譯表會把一個UUID作為ID來自動生成它。Postgresq的uuid-ossp擴(kuò)展插件所用算法和生成UUID的算法是不同的。Rails 4缺省使用的是v4算法. 你可以在這里: http://www.postgresql.org/docs/current/static/uuid-ossp.html 看到更多有關(guān)這些算法的細(xì)節(jié)。
然而,有時(shí)候你不想用UUID作為ID來進(jìn)行替換。那么,你可以另起一列來放置它:
1
2
3
4
5
6
7
8
9
|
class AddUuidToModelsThatNeedIt < ActiveRecord::Migration def up add_column :translations , :uuid , :uuid end def down remove_column :invoices , :uuid end end |
這會創(chuàng)建一個放置UUID的列,但這個UUID不會自動生成。你不得不在Rails中用SecureRandom來生成它。但是,我們認(rèn)為這是一個典型的數(shù)據(jù)庫職責(zé)行為。值得慶幸的是,add_column中的缺省選項(xiàng)會幫我們實(shí)現(xiàn)這種行為:
1
2
3
4
5
6
7
8
9
|
class AddUuidToModelsThatNeedIt < ActiveRecord::Migration def up add_column :translations , :uuid , :uuid , :default => "uuid_generate_v4()" end def down remove_column :invoices , :uuid end end |
現(xiàn)在,UUID能被自動創(chuàng)建了。同理也適用于已有記錄!