2015-11-13 30 views

回答

3

是的,你可以。

首先運行遷移:

create_table 'table' id: false, force: true do |t| 
    t.string 'id', null: false 
end 

指定所述ID的類型string

然後在你的模型:

class Table < ActiveRecord::Base 
    self.primary_key = :id 
end 

這將基本明確指出該字符串id是表實例實例的主鍵。

+0

什麼是力量:真正的意思? –

+0

這裏是一個完美的解釋它的文章:) http://stackoverflow.com/questions/18704290/what-does-force-true-mean-in-the-schema-file – Cyzanfar

0

你也應該考慮在Rails中查找大約uuid的。

儘管它是主要是PostgreSQL一塊的功能,我們發現它與MYSQL工作也很好:

enter image description here

你可以將它設置這樣的:

#app/models/post.rb 
class Post < ActiveRecord::Base 
    before_create :set_uuid 

    private 

    def set_uuid 
     self.uuid = loop do 
     random_token = SecureRandom.hex(5) 
     break random_token unless self.class.exists? random_token 
     end 
    end 
end 

這可以伴隨 - 如Cyzanfar所指出 - 通過用uuid代替id主鍵。 軌道4自動支持uuid ...

def change 
    create_column :posts, :uuid, :string 
    remove_column :posts, :id 
    rename_column :posts, :uuid, :id 
    execute "ALTER TABLE table ADD PRIMARY KEY (uuid);" 
end 

一些參考:

-

由於Rails 4蘇開箱即用的uuid,這應該適合你。

如前所述,我們使用uuid我們的一些車型(它使我們能夠同時保持獨特記錄保持功能)

相關問題