Rails 4 能原生態(tài)的支持Postgres 中的UUID(Universally Unique Identifier,可通用的唯一標(biāo)識符)類型。在此,我將向你描述如何在不用手工修改任何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 看到更多有關(guān)這些算法的細節(jié)。
然而,有時候你不想用UUID作為ID來進行替換。那么,你可以另起一列來放置它:
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來生成它。但是,我們認為這是一個典型的數(shù)據(jù)庫職責(zé)行為。值得慶幸的是,add_column中的缺省選項會幫我們實現(xiàn)這種行為:
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)建了。同理也適用于已有記錄!
您可能感興趣的文章:- 詳細講解PostgreSQL中的全文搜索的用法
- 使用Bucardo5實現(xiàn)PostgreSQL的主數(shù)據(jù)庫復(fù)制
- 在PostgreSQL的基礎(chǔ)上創(chuàng)建一個MongoDB的副本的教程
- 在PostgreSQL中使用數(shù)組時值得注意的一些地方
- 在PostgreSQL中使用日期類型時一些需要注意的地方
- 一個提升PostgreSQL性能的小技巧
- 在PostgreSQL中實現(xiàn)遞歸查詢的教程
- 在PostgreSQL上安裝并使用擴展模塊的教程
- 介紹PostgreSQL中的范圍類型特性
- 深入解讀PostgreSQL中的序列及其相關(guān)函數(shù)的用法