我有一个Mongoid模型,需要两个字段才能是唯一的。我想生成"唯一号码"值和重试,如果它在保存时间内不是唯一的。
class MyModel
include Mongoid::Document
include Mongoid::Timestamps
field :number
field :name
index({ number: 1 }, { unique: true, background: true })
index({ name: 1 }, { unique: true, background: true })
validates_presence_of :number, :name
validates_uniqueness_of :number, :name
def self.make!(name)
find_or_initialize_by(name: name).tap do |model|
if model.new_record?
model.number = generate_random_number
model.save! # fails validation because number is no longer unique
end
end
end
end
如何在发生唯一性碰撞时重试?