【问题标题】:Create a custom prefix on a UUID在 UUID 上创建自定义前缀
【发布时间】:2018-07-30 10:46:38
【问题描述】:

我想知道是否有任何方法可以在 Rails 中的 UUID 上创建自定义前缀。我想生成类似的东西:

"ret_a44691c8-93e2-11e8-ac1c-1b3aa40a1cae"

我找到了这段代码,我可以将其添加到我的迁移中以创建 UUID:

t.uuid "uuid", default: "uuid_generate_v4()"

但这会产生类似的东西:

"a44691c8-93e2-11e8-ac1c-1b3aa40a1cae"

是否可以得到我想要的格式?

【问题讨论】:

  • 您使用的是哪个数据库?
  • 我使用的是 Postgres DB(版本 10)
  • postgres 将 UUID 定义为 as a sequence of lower-case hexadecimal digits, in several groups separated by hyphens, specifically a group of 8 digits followed by three groups of 4 digits followed by a group of 12 digits, for a total of 32 digits representing the 128 bits => postgresql.org/docs/9.1/static/datatype-uuid.html
  • 为什么还要在前面加上ret_
  • @Leo 这会在 Postgres 中引发错误 => sqlfiddle.com/#!17/0f429/2

标签: ruby-on-rails uuid rails-migrations


【解决方案1】:

如 cmets 中所述,postgres 将 UUID 定义为 (https://www.postgresql.org/docs/9.1/static/datatype-uuid.html)

A sequence of lower-case hexadecimal digits, in several groups separated by 
hyphens, specifically a group of 8 digits followed by three groups of 4 digits 
followed by a group of 12 digits, for a total of 32 digits representing the 128 bits

所以你不能在 UUID 列中添加 ret_ 前缀。此外,如果您想识别零售商和客户,您也不应该为其创建另一个列。

SqlFiddle 使用串联 UUID 时。它会抛出一个错误。

【讨论】:

    【解决方案2】:

    如果你想为你的 UUID 加上前缀,你可以在 postgres 中做这样的事情:

    CREATE TABLE IF NOT EXISTS my_table (
      uuid TEXT NOT NULL DEFAULT concat('ret-', uuid_generate_v4())
    );
    

    这将生成一个像这样的 uuid:

    'ret-a44691c8-93e2-11e8-ac1c-1b3aa40a1cae'
    

    【讨论】:

    • 使用convert_to(,) 将列存储为 BYTEA 会更好地进行索引。
    猜你喜欢
    • 2018-01-05
    • 1970-01-01
    • 2014-02-20
    • 2021-03-31
    • 2023-03-03
    • 1970-01-01
    • 2021-11-19
    • 2014-07-08
    • 2021-04-04
    相关资源
    最近更新 更多