Search code examples
ruby-on-railsassociationsvoting

RoR voting system. How to count up votes, down votes, and total votes?


I am trying to create a voting system. The models that are being voted on are Issues and I have another model called Vote that holds an issue_id and a vote value of 0 or 1. The votes are being created with forms with hidden fields. This is on the issues index view.

<h1>Votes</h1>

<% @issues.each do |issue| %>
<li>
    <div class="issue">
        <h2><%= issue.title %></h2>
        <p><%= issue.body %></p>

        <%= form_for(@vote, :remote => true) do |f| %>
        <%= f.hidden_field "issue_id", :value => issue.id %>
        <%= f.hidden_field "vote", :value => 1 %>
        <%= submit_tag "Up", :class => 'up-vote' %>
        <% end %>


        <%= form_for(@vote, :remote => true) do |f| %>
        <%= f.hidden_field "issue_id", :value => issue.id %>
        <%= f.hidden_field "vote", :value => 0 %>
       <%= submit_tag "Down", :class => 'down-vote' %>
        <% end %>

    </div>
</li>
<% end %>

There is a has_many and belongs_to relationship between issues and votes. I want to display the number of up votes and down votes next to the buttons for each issue. So I need to pull all the votes with vote = 1 for each issue, as well as all the ones with vote = 0, and count each. Also want to know total votes. How should I do this? I have counter_cache set on the vote models issue association and votes_count column in my issues schema. Should this work be done in the controller or the model?


Solution

  • I haven't tried it myself, but you should try adding some methods to your Issue model like this:

    def upvote_count
      votes.count(:conditions => "value = 1")
    end
    
    def downvote_count
      votes.count(:conditions => "value = 0")
    end
    

    I learned this in the Rails documentation. You can see for yourself here:

    http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html http://apidock.com/rails/ActiveRecord/Associations/CollectionAssociation/count