From 9bbf0b1ef9a1edba7ca111d06709e4649a39f629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Checa?= Date: Fri, 20 Oct 2017 16:48:54 +0200 Subject: [PATCH] Improved `most_voted` method --- app/controllers/polls/questions_controller.rb | 4 ++++ app/models/poll/question/answer.rb | 17 ++++++++++------- app/views/polls/results.html.erb | 6 +++--- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/app/controllers/polls/questions_controller.rb b/app/controllers/polls/questions_controller.rb index 407e6d984..6345773f2 100644 --- a/app/controllers/polls/questions_controller.rb +++ b/app/controllers/polls/questions_controller.rb @@ -13,6 +13,10 @@ class Polls::QuestionsController < ApplicationController answer.touch if answer.persisted? answer.save! answer.record_voter_participation(token) + @question.question_answers + .where(question_id: @question, title: answer.answer) + .first + .set_most_voted @answers_by_question_id = { @question.id => params[:answer] } end diff --git a/app/models/poll/question/answer.rb b/app/models/poll/question/answer.rb index eff45a57a..8241aa78e 100644 --- a/app/models/poll/question/answer.rb +++ b/app/models/poll/question/answer.rb @@ -13,7 +13,6 @@ class Poll::Question::Answer < ActiveRecord::Base validates :given_order, presence: true, uniqueness: { scope: :question_id } before_validation :set_order, on: :create - before_save :most_voted def description super.try :html_safe @@ -37,15 +36,19 @@ class Poll::Question::Answer < ActiveRecord::Base Poll::Answer.where(question_id: question, answer: title).count end - def most_voted - answers = question.question_answers - .map { |a| Poll::Answer.where(question_id: a.question, answer: a.title).count } - most_voted = !answers.any?{ |a| a > total_votes } - - self.update_attributes(most_voted: most_voted) + def most_voted? + self.most_voted end def total_votes_percentage ((total_votes*100) / question.answers_total_votes).round(2) rescue 0 end + + def set_most_voted + answers = question.question_answers + .map { |a| Poll::Answer.where(question_id: a.question, answer: a.title).count } + is_most_voted = !answers.any?{ |a| a > self.total_votes } + + self.update(most_voted: is_most_voted) + end end diff --git a/app/views/polls/results.html.erb b/app/views/polls/results.html.erb index f0c9e4a38..c8e9cbfab 100644 --- a/app/views/polls/results.html.erb +++ b/app/views/polls/results.html.erb @@ -17,19 +17,19 @@
<%- @poll.questions.each do |question| %> - +

<%= question.title %>

<%- question.question_answers.each do |answer| %> - + <% end %> <%- question.question_answers.each do |answer| %> -
><%= answer.title %>><%= answer.title %>
> + > <%= answer.total_votes %> (<%= answer.total_votes_percentage %>%)