在 Ruby on Rails 中使用随机字符串作为 id? [英] Use a random string as id in Ruby on Rails?

查看:40
本文介绍了在 Ruby on Rails 中使用随机字符串作为 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类似于 http://www.pastebin.com/ 的网络应用Ruby on Rails.pastebin.com 使用随机字符串来标识项目.Ruby on Rails 使用自动递增的数字.如何让 Ruby on Rails 也使用这些随机字符串作为项目的 ID,而不是自动递增的数字?

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?

谢谢

推荐答案

使用有保证的随机字符串生成器,base64 对其进行编码,然后将其缩短为可接受的(8 个字符?)

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"

在 Rails 中,您将根据 :slug 列更改要加载的路由,并使用以下内容设置此值:

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

这篇关于在 Ruby on Rails 中使用随机字符串作为 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆