Ricce
Ricce

Reputation: 69

Rails counting rows with has_many relation

I have:

class Constituency < ActiveRecord::Base
   has_many :votes
end

class Vote <ActiveRecord::Base
   belongs_to :constituency
end

Now, what I want to do is to create a table, that will show me Name of constituency, number of voters (which is easy, as it is part of the table Constituency) and number of votes that were given in this constituency. The beginning looks like this:

<% @constituencies.each do |constituency| %>
  <tr>
    <td><%= constituency.name %></td>
    <td><%= constituency.voters %></td>

So now comes my question: how can I count all rows in Votes, but with division based on constituency?

Upvotes: 1

Views: 83

Answers (1)

sansarp
sansarp

Reputation: 1466

constituency.votes.count should give you the correct count for each different constituency. Hope this helps.

<% @constituencies.each do |constituency| %>
  <tr>
    <td><%= constituency.name %></td>
    <td><%= constituency.voters %></td>
    <td><%= constituency.votes.count %></td>

Upvotes: 1

Related Questions