From 610aea2c72e5238bb9f6ad8b528ebaa986e96b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Checa?= Date: Tue, 17 Oct 2017 18:30:20 +0200 Subject: [PATCH] Added new methods to Poll question and Poll answers --- app/models/poll/question.rb | 4 ++++ app/models/poll/question/answer.rb | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/app/models/poll/question.rb b/app/models/poll/question.rb index 90e528bd0..94a68b806 100644 --- a/app/models/poll/question.rb +++ b/app/models/poll/question.rb @@ -60,4 +60,8 @@ class Poll::Question < ActiveRecord::Base where(poll_id: Poll.answerable_by(user).pluck(:id)) end + def answers_total_votes + question_answers.map { |a| Poll::Answer.where(question_id: self, answer: a.title).count }.sum + end + end diff --git a/app/models/poll/question/answer.rb b/app/models/poll/question/answer.rb index ccbcf1abd..de6e35d1d 100644 --- a/app/models/poll/question/answer.rb +++ b/app/models/poll/question/answer.rb @@ -31,4 +31,18 @@ class Poll::Question::Answer < ActiveRecord::Base def self.last_position(question_id) where(question_id: question_id).maximum('given_order') || 0 end + + def total_votes + Poll::Answer.where(question_id: question, answer: title).count + end + + def is_winner? + answers = question.question_answers + .map { |a| Poll::Answer.where(question_id: a.question, answer: a.title).count } + !answers.any?{ |a| a > total_votes } + end + + def total_votes_percentage + ((total_votes*100) / question.answers_total_votes).round(2) + end end