Rails cannot guarantee uniqueness. You need to create a unique index on the table on [curriculum_sequence_id, student_id]
in the database.
validates uniqueness: { scope: [:foobar] } not working
-
15-07-2023 - |
Pergunta
I have a model that has a uniqueness validation on it something like:
class CurriculumRequirement < ActiveRecord::Base
belongs_to :student
belongs_to :curriculum_sequence
validates :student_id,
uniqueness: { scope: [:curriculum_sequence_id] }
end
The problem is that somehow duplicate records are being inserted into my database despite this validation. The place in which adding these records happens in a sidekiq background worker:
student.curriculum_requirements.where(curriculum_sequence: sequence).first_or_create
I think that what is happening is that 2 or more workers are executing the same code, and saving the record. Is there a way to put a lock or something on this record so that I don't get duplicates?
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow