RAILS - 如何在投票中投票

RAILS - HOW TO ADD VOTES IN A POLL

我是 Rails 的新手,我在这里使用翻译成 post。

我正在练习 rails,为此我设置了一个民意调查(投票)系统。

到那时投票工作正常,投票存储正确,但是,我想在前端设置一个屏幕来显示结果,这就是我遇到困难的地方。

如何从“投票”列的 PollOptions table 中对投票进行求和。我想这样显示它: 姓名:10 票或 X% 的选票 姓名:10 票或 X% 的选票 姓名:10 票或 X% 的选票

据我了解,我需要在控制器中创建一个方法来执行此求和? 任何文档 links/tips,我将不胜感激。

polls_controller

class PollsController < ApplicationController
  def index
    @poll = Poll.where(finished_at: nil).last
    @poll_options = @poll.poll_options.order :name
  end

  def vote 
    @poll_option = PollOption.find params[:poll_option_id]
    @poll_option.increment! :votes
  
    respond_to do |format|
      format.turbo_stream { render :vote }
    end
  end
end

型号: 投票

class Poll < ApplicationRecord
  has_many :poll_options
end

poll_option

class PollOption < ApplicationRecord
  belongs_to :poll
end

在这种情况下,我要调用投票结果。

查看_poll.html.erb

<div id="poll-container" class="col-lg-8 mx-lg-auto">
  <div class="card shadow"> 
    
    <div class="card-header">
      <h2 class="card-title text-center">
      <%= @poll.name %>
      
      <p>
        <%= @poll_options.pluck(:name).to_sentence(last_word_connector: ' ou ') %>
      </h2>
    </div>

    <div class="card-body">
    
      <div class="d-flex flex-column bd-highlight mb-3">
        <% @poll_options.each do |item| %>
          <p>
            <%= button_to vote_url,
                method: :post,  
                class: "btn btn-outline-secondary",
                params: { poll_option_id: item.id } do %> 
            <h2> 
              <%= item.name %> 
              <%= image_tag item.photo, size: "40x40" %>            
            </h2>            
          <% end %>
        <% end %>
      </div>
    </div>
  </div>
</div>

https://i.stack.imgur.com/JQfQP.png

提前感谢您的指导。

您可以使用 ActiveRecord::Calculations sum (.sum(:votes)) 对 poll_optionsvotes 列的所有行求和。

要查找投票的所有选票,您需要以下内容

@poll.poll_options.sum(:votes)

然后为 PHP 创建 % 例如你可以做

total_votes = @poll.poll_options.sum(:votes)
php_votes = @poll.poll_options.where(name: 'PHP').votes
(php_votes / total_votes).to_i * 100