Avoid error for polls results

When a poll is created, and any of the questions for that poll doesn't
have any answer created, the following exception was raised when
trying to see the results:

Failure/Error: question_answers.max_by {|answer| answer.total_votes }.id

  ActionView::Template::Error:
    undefined method `id' for nil:NilClass
      ./app/models/poll/question.rb:66:in `most_voted_answer_id'
This commit is contained in:
Julian Herrero
2019-06-11 15:57:19 +02:00
committed by Javi Martín
parent 6bcf8ea806
commit 629c75ceeb
2 changed files with 10 additions and 1 deletions

View File

@@ -67,7 +67,7 @@ class Poll::Question < ApplicationRecord
end
def most_voted_answer_id
question_answers.max_by(&:total_votes).id
question_answers.max_by(&:total_votes)&.id
end
def possible_answers

View File

@@ -52,4 +52,13 @@ describe "Poll Results" do
expect(find("#answer_#{answer5.id}_result")).to have_content("1 (33.33%)")
end
end
scenario "Results for polls with questions but without answers" do
poll = create(:poll, :expired, results_enabled: true)
question = create(:poll_question, poll: poll)
visit results_poll_path(poll)
expect(page).to have_content question.title
end
end