Use a random string as id in Ruby on Rails?
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 number. How can I make Ruby on Rails also use these random strings as IDs for items, instead of auto开发者_如何学编程-incrementing numbers?
Thanks
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
I believe you can override the implementation of to_param in the models of interest. There's a fuller explanation of the technique here
For vanilla ruby
require 'securerandom'
require 'base64'
slug = Base64.encode64(SecureRandom.uuid)[0..10]
=> "YWVkNzZmYjI"
=> "MzQxMDkxY2U"
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
精彩评论