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.
71 lines
2.3 KiB
Ruby
71 lines
2.3 KiB
Ruby
class Polls::AnswersController < ApplicationController
|
|
|
|
load_and_authorize_resource :poll
|
|
load_and_authorize_resource :question, class: "Poll::Question"
|
|
authorize_resource :answer, class: "Poll::Answer"
|
|
|
|
def create
|
|
@question = Poll::Question.find_by(id: params[:id])
|
|
if @question.votation_type.open? && !check_question_answer_exist
|
|
@question.question_answers.create(
|
|
title: params[:answer],
|
|
given_order: @question.question_answers.maximum(:given_order).to_i + 1,
|
|
hidden: false
|
|
)
|
|
flash.now[:notice] = t("dashboard.polls.index.succesfull")
|
|
else
|
|
flash.now[:alert] = "Unfortunately failed to sent"
|
|
end
|
|
load_for_answers
|
|
if @question.enum_type&.include?("answer_couples")
|
|
last_pair ||= generate_and_store_new_pair(@question)
|
|
@last_pair_question_answers = { @question.id => last_pair }
|
|
end
|
|
render "polls/questions/answer", format: :js
|
|
end
|
|
|
|
def delete
|
|
@question = Poll::Question.find_by(id: params[:id])
|
|
!@question.answers.find_by(author: current_user, answer: params[:answer]).destroy
|
|
@question.question_answers.each do |question_answer|
|
|
question_answer.set_most_voted
|
|
end
|
|
question_answers
|
|
load_for_answers
|
|
if @question.enum_type&.include?("answer_couples")
|
|
last_pair ||= generate_and_store_new_pair(@question)
|
|
@last_pair_question_answers = { @question.id => last_pair }
|
|
end
|
|
render "polls/questions/answer", format: :js
|
|
end
|
|
|
|
private
|
|
|
|
def check_question_answer_exist
|
|
exist = false
|
|
@question.question_answers.each do |question_answer|
|
|
break if exist
|
|
exist = true if question_answer.title == params[:answer]
|
|
end
|
|
exist
|
|
end
|
|
|
|
def load_for_answers
|
|
@page = params[:page].presence || 1
|
|
question_answers
|
|
@answers_by_question_id = { @question.id => @question.answers
|
|
.by_author(current_user)
|
|
.order(:order)
|
|
.pluck(:answer) }
|
|
end
|
|
|
|
def question_answers
|
|
if @question.is_positive_negative?
|
|
@answers = @question.question_answers.visibles.page(params[:page])
|
|
else
|
|
@answers = @question.question_answers.visibles
|
|
end
|
|
end
|
|
|
|
end
|