What could be the reason for duplicate records being written to the database days apart? In my create action, I first check if a record with a unique identifier exists, and updates it if it exists or else creates a new record. But right now in my database I'm seeing duplicate records that are not only seconds or minutes apart, but even days or months apart. What could be causing this?
将重复记录写入数据库的原因可能是什么?在我的创建操作中,我首先检查是否存在具有唯一标识符的记录,如果存在则更新它,否则创建新记录。但是现在在我的数据库中,我看到的重复记录不仅相隔几秒或几分钟,而且相隔甚至几天或几个月。可能是什么导致了这个?
def create
record_uid = params.delete(:uid)
if record_uid.present?
record = Record.find_by(uid: record_uid)
unless record.present?
redirect_to error_path and return
end
else
record = Record.new
end
record.attributes = params
record.save
redirect_to record
end
1 个解决方案
#1
1
There are several options:
有几种选择:
- Create db-level uniq constraint. Here is a SO answer that can help you. Based on your code I would suggest to create uniq btree index for uid column.
- 创建db-level uniq约束。这是一个可以帮助你的答案。基于您的代码,我建议为uid列创建uniq btree索引。
-
Create model-level uniq constraint with
ActiveModel
validations:使用ActiveModel验证创建模型级uniq约束:
class Record < ActiveRecord::Base validates :uid, uniqueness: true end
First option will raise ActiveRecord::RecordNotUnique
and on second record.save
will return false
so you need to handle that either way
第一个选项将引发ActiveRecord :: RecordNotUnique,第二个record.save将返回false,因此您需要处理这两种方式
#1
1
There are several options:
有几种选择:
- Create db-level uniq constraint. Here is a SO answer that can help you. Based on your code I would suggest to create uniq btree index for uid column.
- 创建db-level uniq约束。这是一个可以帮助你的答案。基于您的代码,我建议为uid列创建uniq btree索引。
-
Create model-level uniq constraint with
ActiveModel
validations:使用ActiveModel验证创建模型级uniq约束:
class Record < ActiveRecord::Base validates :uid, uniqueness: true end
First option will raise ActiveRecord::RecordNotUnique
and on second record.save
will return false
so you need to handle that either way
第一个选项将引发ActiveRecord :: RecordNotUnique,第二个record.save将返回false,因此您需要处理这两种方式