mardi 18 février 2020

2 entries created by using activerecord find_or_initialize_by followed by update_attributes

I am using find_or_initialize_by followed by update_attributes to create new entry else update if entry already exists.

below is the code snippet in Ruby.

StudentResult.find_or_initialize_by(
        :course_id => course_id,
        :student_id => student_id,
        :assessment_id => assignment_id,
        ).update_attributes!(
        :total_score => assignment_total_score,
        :score => assignment_score
)

But I can see there are 2 entries for the same combination of course_id, student_id, assessment_id. This is happening rarely for some records only.

course_id, student_id, assessment_id , total_score, score, created_at , updated_at
7779,156035,29792,30,0,2020-02-06 13:54:30.325446,2020-02-06 13:54:30.325446
7779,156035,29792,30,0,2020-02-06 13:54:30.326769,2020-02-06 13:54:30.326769

Currently I do not have any unique key constraints on table StudentResult. But ideally it should create only 1 entry for course_id, student_id and assessment_id combination. I am skeptical that can this be due to some race conditions or I am missing something in my code.

1 commentaire:

  1. Do this hack to drop 2lb of fat in 8 hours

    Well over 160,000 men and women are losing weight with a simple and secret "water hack" to burn 1-2lbs every night while they sleep.

    It's proven and it works all the time.

    This is how to do it yourself:

    1) Go grab a clear glass and fill it up with water half full

    2) And now follow this strange HACK

    and become 1-2lbs lighter the very next day!

    RépondreSupprimer