使用 Rails 即时生成独特的令牌 [英] Generating unique token on the fly with Rails
问题描述
我想在我的控制器中为user_info_token"列中的用户生成一个令牌.但是,我想检查当前没有用户拥有该令牌.这段代码就够了吗?
I want to generate a token in my controller for a user in the "user_info_token" column. However, I want to check that no user currently has that token. Would this code suffice?
begin
@new_token = SecureRandom.urlsafe_base64
user = User.find_by_user_info_token(@new_token)
end while user != nil
@seller.user_info_token = @new_token
或者有更简洁的方法来做到这一点吗?
Or is there a much cleaner way to do this?
推荐答案
我找到的最干净的解决方案:
The cleanest solution I found:
@seller.user_info_token = loop do
token = SecureRandom.urlsafe_base64
break token unless User.exists?(user_info_token: token)
end
一些非常干净但可能重复的东西(虽然很少):
And something very clean but with potential duplicates (very few though):
@seller.user_info_token = SecureRandom.uuid
当然,为您的 :user_info_token
添加唯一索引.搜索具有相同令牌的用户会更快并且如果偶然有 2 个用户在同一时刻使用完全相同的令牌被保存,它将引发异常!
of course, add a unique index to your :user_info_token
. It will be much quicker to search for a user with the same token and it will raise an exception if by chance, 2 users are saved at the exact same moment with the exact same token!
这篇关于使用 Rails 即时生成独特的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!