gpt4 book ai didi

ruby-on-rails - 将数字添加到正则表达式?

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:58 25 4
gpt4 key购买 nike

我们有一个带有 Google 登录/注册的 Facebook 应用程序。一些帐户不提供用户名,因此应用程序必须在将对象保存到数据库之前创建一个用户名。

我们目前是这样解决问题的:

user.username = "#{user.email[/^[^@]*/]}_#{user.id.to_s}"

问题是,我们使用 mongodb/mongoid 就像 database/odm 并生成一个太长的用户名,比如:

hyperrjas_50ad43d11d41c86b27000066

在这种情况下,我们在 hyperrjas 之后添加了 user.id

如果用户名已被占用,我们想添加一个唯一的编号而不是唯一的 id,例如:

hyperrjas
hyperrjas1
hyperrjas2
hyperrjas3
...

我们该怎么做?

最佳答案

我之前回答过类似的问题。这是我想出的:

https://stackoverflow.com/a/13794784/367611

根据评论更新

您可以通过以下方式创建一个方法:

def prevent_collision(user)
name = "#{user.email[/^[^@]*/]}"
users = User.where(:username => /^#{name}/).to_a #Return an array and after use length method with users.length. Without .to_a is not working because is returned a mongoid criteria.
count = users.length

if count > 0
count = rand(1000)
loop do
break "#{name}#{count}" unless users.any? { |u| u.name == "#{name}#{count}" }
count += rand(10)
end
else
name
end
end

其中返回值将是最初生成的名称或附加了计数的名称。然后你可以这样做,例如:

@user.username = prevent_collision(@user)
@user.save

关于ruby-on-rails - 将数字添加到正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13864074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com