Use a random string as id in Ruby on Rails?

后端 未结 4 714
暖寄归人
暖寄归人 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:02

    I believe you can override the implementation of to_param in the models of interest. There's a fuller explanation of the technique here

    0 讨论(0)
  • 2021-02-06 19:04

    generate a random string as key and put it into a db table? make sure the key is uniq?

    base="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    (0...10).map{base[rand(base.length)]}.join
    
    0 讨论(0)
  • 2021-02-06 19:17

    For vanilla ruby

    require 'securerandom'
    require 'base64'
    
    slug = Base64.encode64(SecureRandom.uuid)[0..10]
    => "YWVkNzZmYjI" 
    => "MzQxMDkxY2U"
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题