Add votes_for(option) method and simplify results template

Move the summing logic from the template into the component. Introduce
a votes_for(option) method that looks up grouped partial results and
returns the total amount or 0.
This commit is contained in:
taitus
2025-09-16 15:19:11 +02:00
parent 7565fc5fc2
commit e3e475b4df
2 changed files with 10 additions and 3 deletions

View File

@@ -11,7 +11,7 @@
<% question.question_options.each_with_index do |option, i| %> <% question.question_options.each_with_index do |option, i| %>
<tr id="question_<%= question.id %>_<%= i %>_result"> <tr id="question_<%= question.id %>_<%= i %>_result">
<td><%= option.title %></td> <td><%= option.title %></td>
<td class="text-center"><%= by_answer[option.title].present? ? by_answer[option.title].sum(&:amount) : 0 %></td> <td class="text-center"><%= votes_for(option) %></td>
</tr> </tr>
<% end %> <% end %>
</tbody> </tbody>

View File

@@ -6,7 +6,14 @@ class Admin::Poll::Results::QuestionComponent < ApplicationComponent
@partial_results = partial_results @partial_results = partial_results
end end
def by_answer def votes_for(option)
@by_answer ||= partial_results.where(question: question).group_by(&:answer) grouped = by_answer[option.title] || []
grouped.sum(&:amount)
end end
private
def by_answer
@by_answer ||= partial_results.where(question: question).group_by(&:answer)
end
end end