本文介绍了Rails验证并发输入的唯一性失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Ticket模型,该模型对字符串属性ticket_number

I have a Ticket model with basic uniqueness validation on a string attribute ticket_number

validates :ticket_number, uniqueness: true

这是ticket_number

<%= f.number_field :ticket_number, :value => @ticket.ticket_number || (Ticket.exists? ? Ticket.maximum(:ticket_number).next) : 1 , :class => 'form-control' %>

验证似乎按预期进行,但是当我们部署该应用程序并且可能有多个用户同时进入tickets时,这应该不会引起问题(对吗?),我们发现重复的记录(相同票证号)在数据库(MySQL)中.

The validation seems to work as expected, however when we deployed the app and probably more than one users were entering tickets at the same time, which shouldn't cause an issue (right?) we found duplicated records (same ticket number) in the database(MySQL).

到目前为止,在总共600多张门票中只发生过一次,但是为什么以及如何防止这种情况发生?

It only happened once in a total of 600+ tickets so far but why and how to prevent that from happening ?

推荐答案

这很不常见,您可能很不幸,它有可能.

This is very uncommon and you're probably very unlucky that it has, it is possible.

阅读: https ://github.com/rails/rails/blob/master/activerecord/lib/active_record/validations/uniqueness.rb#L165

Read: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/validations/uniqueness.rb#L165

请考虑以下内容: 用户A提交表单

Consider the following: User A submits form

  • 用户A提交表单
  • Rails检查数据库中用户A的现有ID-未找到
  • 用户B提交表单
  • Rails检查数据库中用户B的现有ID-未找到
  • Rails保存用户A记录
  • Rails保存用户B记录

所有这些操作必须在几毫秒内发生,但从技术上讲是可能的.

All this has to happen within milliseconds but it is technically possible.

我建议在数据库级别(主键)添加一个约束.

I'd suggest adding a constraint at the database level (primary key).

这篇关于Rails验证并发输入的唯一性失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 21:06