Generating unique token on the fly with Rails

前端 未结 6 1471
醉话见心
醉话见心 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:48

    You can try some below tricks to get unique token, its so easy which I used in my project -

    CREDIT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
    def create_credit_key(count = 25)
        credit_key = ""
        key = CREDIT_CHARS.length
        for i in 1..count
          rand = Random.rand((0.0)..(1.0))
          credit_key += CREDIT_CHARS[(key*rand).to_i].to_s
        end 
        return credit_key
      end
    

    Using digest it is again more easy, here I tried to generate without using any algorithm.

提交回复
热议问题