From eb083bdbc28904beb55c0a9dfae664c578dbf577 Mon Sep 17 00:00:00 2001 From: kaitoyama <45167401+kaitoyama@users.noreply.github.com> Date: Thu, 2 May 2024 13:26:09 +0900 Subject: [PATCH] impl delete duplicate answer --- model/respondents_impl.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/model/respondents_impl.go b/model/respondents_impl.go index 29019230..74b14742 100755 --- a/model/respondents_impl.go +++ b/model/respondents_impl.go @@ -72,7 +72,19 @@ func (*Respondent) InsertRespondent(ctx context.Context, userID string, question return 0, fmt.Errorf("failed to get tx: %w", err) } + var questionnaire Questionnaires var respondent Respondents + + err = db. + Where("id = ?", questionnaireID). + First(&questionnaire).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return 0, ErrRecordNotFound + } + if err != nil { + return 0, fmt.Errorf("failed to get questionnaire: %w", err) + } + if submittedAt.Valid { respondent = Respondents{ QuestionnaireID: questionnaireID, @@ -86,12 +98,28 @@ func (*Respondent) InsertRespondent(ctx context.Context, userID string, question } } + if !questionnaire.IsDuplicateAnswerAllowed && submittedAt.Valid { + // delete old answers + err = db. + Where("questionnaire_id = ? AND user_traqid = ?", questionnaireID, userID). + Delete(&Respondents{}).Error + // 既存の回答がなかった場合はそのまま進む + if errors.Is(err, ErrNoRecordDeleted) { + err = nil + } + if err != nil { + return 0, fmt.Errorf("failed to delete old answers: %w", err) + } + + } + err = db.Create(&respondent).Error if err != nil { return 0, fmt.Errorf("failed to insert a respondent record: %w", err) } return respondent.ResponseID, nil + } // UpdateSubmittedAt 投稿日時更新