Home > Enterprise >  RAILS - HOW TO ADD VOTES IN A POLL
RAILS - HOW TO ADD VOTES IN A POLL

Time:05-02

I'm new to Rails and I'm using translate to post here.

I'm practicing rails and for that I set up a poll (voting) system.

Until then the voting is working normally, the votes are stored correctly, however, I would like to set up a screen on the frontend to display the result, and that's where I'm having difficulty.

How can I sum the votes from the PollOptions table of the "Votes" column. I would like to display it like this: name: 10 votes or X% of votes name: 10 votes or X% of votes name: 10 votes or X% of votes

As I understand it, I need to create a method in the controller that will do this sum? Any documentation links/tips, I'd appreciate it.

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

model: poll

class Poll < ApplicationRecord
  has_many :poll_options
end

poll_option

class PollOption < ApplicationRecord
  belongs_to :poll
end

In this view, I would like to call the result of the vote.

view _poll.html.erb

<div id="poll-container" >
  <div > 
    
    <div >
      <h2 >
      <%= @poll.name %>
      
      <p>
        <%= @poll_options.pluck(:name).to_sentence(last_word_connector: ' ou ') %>
      </h2>
    </div>

    <div >
    
      <div >
        <% @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

Thanks in advance for any guidance.

CodePudding user response:

You can use ActiveRecord::Calculations sum (.sum(:votes)) to sum all the rows for the votes column under poll_options.

To find all the votes of a poll you need the following

@poll.poll_options.sum(:votes)

Then to create the % for the PHP for example you could do

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