2015-11-13 52 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我们的一些车型(它使我们能够同时保持独特记录保持功能)

相关问题