看起来默认的:id是整数,我能把它变成一个字符串吗?
发布于 2015-11-14 05:41:31
是的你可以。
首先运行迁移:
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是对象实例的主键。
发布于 2015-11-14 17:43:01
您还应该考虑查找uuid在Rails中的内容。
尽管它主要是PostgreSQL的一部分功能,但我们发现它在MYSQL上也工作得很好:

你可以这样设置它:
#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所指出的,可以通过将id主键替换为uuid来实现这一点。Rails 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一些参考资料:
--
因为Rails4开箱即支持uuid,所以这对您来说应该是有效的。
如前所述,我们在一些模型中使用了uuid (它允许我们在保持记录唯一性的同时维护功能)
https://stackoverflow.com/questions/33702103
复制相似问题