Fix duplicate given order creating answers

It's possible to have a given order greater than the number of answers;
we don't have any validation rules for that. So the check for the number
of answers isn't enough.

Checking the maximum given order in the answers is safer. Another option
would be to reorder the answers every time we add a new one, but I'm not
sure whether that's the expected behaviour.

Note even after this change the action is not thread-safe, as it is
possible to create two questions with the same given order with two
simultaneous requests.
This commit is contained in:
Javi Martín
2019-10-10 00:23:20 +02:00
parent 575b4bf978
commit 56e62a41b6
2 changed files with 12 additions and 1 deletions

View File

@@ -9,7 +9,7 @@ class Polls::AnswersController < ApplicationController
if @question.votation_type.open? && !check_question_answer_exist
@question.question_answers.create(
title: params[:answer],
given_order: @question.question_answers.count + 1,
given_order: @question.question_answers.maximum(:given_order).to_i + 1,
hidden: false
)
flash.now[:notice] = t("dashboard.polls.index.succesfull")

View File

@@ -320,6 +320,17 @@ describe "Poll Votation Type" do
expect(page).to have_link "Added answer", class: "answered"
end
end
scenario "existing given order is bigger than the number of answers", :js do
answer1.update(given_order: question.question_answers.count + 1)
visit poll_path(poll_current)
fill_in "answer", with: "Added answer"
click_button "Add answer"
expect(page).to have_link "Added answer"
end
end
context "Answers set" do