Generating unique token on the fly with Rails

前端 未结 6 1458
醉话见心
醉话见心 2021-01-31 18:50

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

6条回答
  •  醉梦人生
    2021-01-31 19:38

    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
    

    Random UUID probability of duplicates

    Edit: 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!

提交回复
热议问题