Add missing validation rule to poll answers

We were checking we didn't have more votes than allowed in the case of
questions with multiple answers, but we weren't checking it in the case
of questions with a single answer. This made it possible to create more
than one answer to the same question. This could happen because the
method `find_or_initialize_user_answer` might initialize two answers in
different threads, due to a race condition.
This commit is contained in:
Javi Martín
2024-05-10 01:44:23 +02:00
parent 6aafc107ae
commit a54d424aed
3 changed files with 71 additions and 20 deletions

View File

@@ -28,7 +28,7 @@ class Poll::Question < ApplicationRecord
accepts_nested_attributes_for :question_options, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :votation_type
delegate :max_votes, :multiple?, :vote_type, to: :votation_type, allow_nil: true
delegate :multiple?, :vote_type, to: :votation_type, allow_nil: true
scope :by_poll_id, ->(poll_id) { where(poll_id: poll_id) }
@@ -90,6 +90,14 @@ class Poll::Question < ApplicationRecord
votation_type.nil? || votation_type.unique?
end
def max_votes
if multiple?
votation_type.max_votes
else
1
end
end
def find_or_initialize_user_answer(user, title)
answer = answers.find_or_initialize_by(find_by_attributes(user, title))
answer.answer = title