生成用于识别记录的唯一随机字符串 [英] Generating unique random string for identifying a record

查看:50
本文介绍了生成用于识别记录的唯一随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够通过唯一键识别表中的记录,在本例中是用户表,该键不会泄露表中记录的顺序.

I have a requirement to be able to identify a record in a table, in this case a user table, by a unique key which does not give away the ordering of the records in the table.

目前我有主键字段,生成的路由如下所示:

Currently I have primary key field and the routes that are generated look like:

/users/1

但是,我希望能够生成如下路线:

However, I'd like to be able to generate a route like:

/users/kfjslncdk

我可以在路由端、数据库端等连接所有东西.但我不确定在 rails 中生成唯一字符串标识符的最佳方法是什么.我想做类似的事情:

I can wire everything up on the route side, database side etc.. but I'm not sure what the best way to generate a unique string identifier would be in rails. I'd like do something like:

before_save :create_unique_identifier

def create_unique_identifier
    self.unique_identifier = ... magic goes here ...
end

我想我可以使用使用 UUIDTools 创建的 guid 的第一部分,但我需要在保存用户之前检查以确保它是唯一的.

I was thinking I could use the first part of a guid created using UUIDTools, but I'd need to check to make sure it was unique before saving the user.

任何建议将不胜感激!

推荐答案

before_create :create_unique_identifier

def create_unique_identifier
  loop do
    self. unique_identifier = SecureRandom.hex(5) # or whatever you chose like UUID tools
    break unless self.class.exists?(:unique_identifier => unique_identifier)
  end
end

这篇关于生成用于识别记录的唯一随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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