我是 ruby on Rails 的新手。我想为每个客户生成唯一的 token 。我可以使用 SecureRandom.hex(6) 生成唯一 token ,但随后我必须检查数据库中是否存在该值,如果数据库很大,则非常耗时。我可以将当前时间附加到 secureadnom.hex(6) 函数,但如果 Rails 同时处理两个请求,则无法保证唯一性。
有人可以告诉我在不进行数据库级别查询的情况下生成唯一 token 的最佳方法吗?
谢谢
最佳答案
为了保证生成的 token 是唯一的,您可以对索引设置唯一约束。 然后在您的代码中您可以处理异常。
示例
begin
#generate your code here and try to save it.
rescue ActiveRecord::RecordInvalid => e
#If exception occurs then again repeat the same process for another hex code and save it.
end
关于mysql - rails : how to insert unique value into the database without duplication?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31426098/