mysql - rails : how to insert unique value into the database without duplication?

标签 mysql ruby-on-rails ruby-on-rails-3

我是 ruby​​ on Rails 的新手。我想为每个客户生成唯一的 token 。我可以使用 SecureRandom.hex(6) 生成唯一 token ,但随后我必须检查数据库中是否存在该值,如果数据库很大,则非常耗时。我可以将当​​前时间附加到 secureadnom.hex(6) 函数,但如果 R​​ails 同时处理两个请求,则无法保证唯一性。

有人可以告诉我在不进行数据库级别查询的情况下生成唯一 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/

相关文章:

ruby-on-rails - rails : sort a has_many using :order is not working due to order by timestamp

mysql - LOAD DATA LOCAL INFILE 导致 mysql2 gem 出现 Malformed packet error

javascript - 如何通过 JavaScript 删除或清除 Google map 标记?

使用sqlite3查询时MySQL语法错误

ruby-on-rails - unicorn ,capistrano 安装

ruby-on-rails - 如何在 Ruby on Rails 中复制记录及其相关记录?

MySQL:错误代码:1242 子查询返回超过 1 行

php将多个用户登录后重定向到多个页面

ruby-on-rails - 无法弄清楚这个 Rails 错误 : undefined method `remember_token=' for #<User:0x00000005e44238>?

xml - rails 3 渲染 xml 而不管 request.format