Rails - 保存的 uuid 长度短于 32 个字符

发布于 2024-10-01 12:51:20 字数 595 浏览 2 评论 0原文

我希望生成一个不可猜测的 ID(即长串随机字符)。

我目前正在使用 https://github.com/sporkmonger/uuidtools

app/helpers/uuidhelper.rb

require 'rubygems'
require 'uuidtools'
module UuidHelper
  def before_create()
    self.id = UUIDTools::UUID.random_create().to_s
  end
end

app/models/mymodel.rb

include UuidHelper

但是,这并没有给我想要的效果,即长度总是太短。

有没有办法使用调整来强制更大的值?我应该使用另一种方法吗?

我目前正在使用 SQLite 作为我的开发数据库。这能起到一些作用吗?

我还假设我应该在将 ID 分配给新实例之前检查该 ID 是否已经存在?

I am looking to generate an ID that is not guessable (i.e. long string of random characters).

I am currently using https://github.com/sporkmonger/uuidtools:

app/helpers/uuidhelper.rb

require 'rubygems'
require 'uuidtools'
module UuidHelper
  def before_create()
    self.id = UUIDTools::UUID.random_create().to_s
  end
end

app/models/mymodel.rb

include UuidHelper

However, this is not giving me the desired effect, i.e. length is always too short.

Is there a way to use adapt this to force larger values? Is there another approach that I should be using?

I am currently using SQLite for my development database. Could this have some effect?

I also assume that I should check if the ID exists already before assigning it to a new instance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

标点 2024-10-08 12:51:20

您可以使用:

require 'digest/sha1'
#to check if generated id is unique
self.id = Digest::SHA1.hexdigest(DateTime.now.to_s)[0..length-1] while (ModelName.find(self.id))

其中 length - 输出 UUID 的所需长度,还必须检查它是否唯一(如果长度太小,这可能是错误的)和 ModelName - 模型的名称

You can use:

require 'digest/sha1'
#to check if generated id is unique
self.id = Digest::SHA1.hexdigest(DateTime.now.to_s)[0..length-1] while (ModelName.find(self.id))

where length - desired length of output UUID, also you must check it to be unique( which could be false, if length is too small) and ModelName - name of your model

旧街凉风 2024-10-08 12:51:20

导致问题的是 SQLite 数据库 - 移至 MySQL 数据库并且它按预期工作。

It was the SQLite database that was causing the issue - moved to MySQL database and it works as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文