Use a random string as id in Ruby on Rails?

后端 未结 4 767
暖寄归人
暖寄归人 2021-02-06 18:45

I want to create a web app similar to http://www.pastebin.com/ in Ruby on Rails. pastebin.com uses a random string to identify an item. Ruby on Rails uses an auto-incrementing n

4条回答
  •  不要未来只要你来
    2021-02-06 19:26

    Use a guaranteed random string generator, base64 encode it and then shorten it to something acceptable (8 characters?)

    require 'uuidtools'
    require 'base64'
    uid = UUIDTools::UUID.random_create
    Base64.encode64(uid)[0..7]
    => "Y2I2ZTQ5"
    

    In Rails you would alter your routes to load based on a :slug column, and set this value using something like this:

    before_create do
      self.slug = Base64.encode64(UUIDTools::UUID.random_create)[0..8]
    end
    

提交回复
热议问题