在Ruby on Rails中为每个用户分配唯一的100个字符散列 [英] Assigning Each User a Unique 100 character Hash in Ruby on Rails

查看:89
本文介绍了在Ruby on Rails中为每个用户分配唯一的100个字符散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上有一个表格,可以从访问者那里获取一些个人信息。我将这些信息传递给另一个服务,我需要为这些表单中的每一个提交一个100个字符的唯一散列值,并将其存储在带有记录的数据库中。生成这个密钥的最佳方式是什么,并确保它是唯一的?

ActiveSupport :: SecureRandom.hex( 50)

这个不是唯一的机会是天文数字。
$

 class MyModel< b $ p 

替换简单的不缩放竞争条件失败解决方案。 ActiveRecord :: Base
before_create:assign_unique_token
$ b $ private
$ b def assign_unique_token
self.unique_token = ActiveSupport :: SecureRandom.hex(50)until unique_token?
结束

def unique_token?
self.class.count(:conditions => {:unique_token => unique_token})== 0
end
end
pre>

如果您确实想确保在列上创建唯一索引,并通过重试来处理数据库唯一性错误,类似于我上面的实现。


I have a form on a website that takes in some personal information from the visitor. I'm passing this information to another service and I need to assign each one of these form submits a 100 character unique hash to be stored in the DB with the record. What's the optimal way to generate this key and make sure it's unique? It's okay if the key auto-increments.

解决方案

ActiveSupport::SecureRandom.hex(50)

The chance of this not being unique is astronomical.

Alternate simple "does not scale" race condition fail solution.

class MyModel < ActiveRecord::Base
  before_create :assign_unique_token

  private

  def assign_unique_token
    self.unique_token = ActiveSupport::SecureRandom.hex(50) until unique_token?
  end

  def unique_token?
    self.class.count(:conditions => {:unique_token => unique_token}) == 0
  end
end

If you really want to make sure, make an unique index on the column, and handle a DB uniqueness error by retrying, similar to my implementation above.

这篇关于在Ruby on Rails中为每个用户分配唯一的100个字符散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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