为rails中的16位二进制数据类型生成uuid
我已经使用了这个'SecureRandom.uuid',但是它占用了很大的空间。 它需要很大的大小,并且我具有binary(16)数据类型和大小,database = mysql; uuid = SecureRandom.uuid
我想要16个大小的uuid并以二进制数据类型存储。
答案 0 :(得分:1)
尝试一下:
require 'securerandom'
uuid = SecureRandom.hex 16
在典型模型中,您会这样做:
before_create :set_uuid
def set_uuid
self.uuid ||= SecureRandom.hex 16 # or self.id, whatever your attribute is named
end
如果使用的是PG,它对UUID的支持很好,而对性能的影响很小,因此您只需在迁移中定义uuid列即可。 https://lab.io/articles/2017/04/13/uuids-rails-5-1/