Question

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?

Was it helpful?

Solution

Rails cannot guarantee uniqueness. You need to create a unique index on the table on [curriculum_sequence_id, student_id] in the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top