如何在 Rails 中覆盖 PostgreSQL 的 gen_random_uuid()?

How can I override PostgreSQL's gen_random_uuid() in Rails?

提问人:supersaidso 提问时间:10/12/2023 更新时间:10/12/2023 访问量:40

问:

我想在PostgreSQL的gen_random_uuid()生成的uuid前面添加一个字符串,以用作我的一个模型的uuid(它不会是主键)。

想想 Stripe 的价格和客户 ID,以及"price_xxxx...""cus_xxxx..."

目前我正在像这样使用 gen_random_uuid():

t.uuid "uuid", default: -> { "gen_random_uuid()" }, null: false

有没有可能做这样的事情,

t.uuid "uuid", default: -> { "xxx" + "gen_random_uuid()" }, null: false

?

Ruby-on-Rails PostgreSQL Ruby-on-Rails-7 pgcrypto

评论

1赞 Tom Lord 10/12/2023
不能使用 rails 覆盖 Postgres 函数。但是你可以使用不同的postgres函数,或者完全停止依赖postgres函数(即在rails应用程序级别设置默认值,而不是在数据库级别)。
0赞 Tom Lord 10/12/2023
关于你的建议,我还没有尝试过,但这有效吗?default: -> { "'xxx' + gen_random_uuid()" }
0赞 supersaidso 10/12/2023
@TomLord谢谢,仅仅在 Rails 应用程序级别设置它有什么明显的缺点吗?
0赞 supersaidso 10/12/2023
@TomLord,我尝试在迁移中以这种方式设置它并得到syntax error, unexpected '}', expecting => ... "xxx_" + "gen_random_uuid()" }
0赞 Tom Lord 10/12/2023
请注意我使用的双括号和单括号。我不确定你到底写了什么来得到这个错误,但它可能是由一些不匹配引起的。

答:

1赞 Arctodus 10/12/2023 #1

在模型级别求解它可能是一种选择

class MyModel < ApplicationRecord
  attribute :uuid, default: -> { "xxx_#{SecureRandom.uuid}" }
end

评论

0赞 supersaidso 10/12/2023
谢谢,我想到了这一点,我只是认为如果我在数据库级别这样做,性能会更好。不过,我不知道收益是微不足道的还是不存在的。这种解决方案在实践中如何运作?uuid 是在实例化记录时定义为此默认值,还是在实例化后更新?
1赞 Lorin Thwaits 10/12/2023 #2

如果您想要特定于 Postgres 的解决方案,请尝试以下操作:

t.uuid 'uuid', default: -> { "'xxx' || gen_random_uuid()" }, null: false

(Postgres 通过 ||(进行字符串连接),并将“ticks”(撇号)中的文本识别为字符串。

评论

0赞 supersaidso 10/12/2023
哦,太棒了,谢谢!