Improved most_voted method
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,19 +17,19 @@
|
||||
|
||||
<div class="small-12 medium-9 column">
|
||||
<%- @poll.questions.each do |question| %>
|
||||
<table>
|
||||
<table id="question_<%= question.id %>_results_table">
|
||||
<h3 anchor="<%= question.title.parameterize %>"><%= question.title %></h3>
|
||||
<thead>
|
||||
<tr>
|
||||
<%- question.question_answers.each do |answer| %>
|
||||
<th scope="col" <%= answer.is_winner? ? "class=win" : "" %>><%= answer.title %></th>
|
||||
<th scope="col" <%= answer.most_voted? ? "class=win" : "" %>><%= answer.title %></th>
|
||||
<% end %>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<%- question.question_answers.each do |answer| %>
|
||||
<td <%= answer.is_winner? ? "class=win" : "" %>>
|
||||
<td id="answer_<%= answer.id %>_result" <%= answer.most_voted? ? "class=win" : "" %>>
|
||||
<%= answer.total_votes %>
|
||||
(<%= answer.total_votes_percentage %>%)
|
||||
</td>
|
||||
|
||||
Reference in New Issue
Block a user