Group and count in Rails
Posted
by alamodey
on Stack Overflow
See other posts from Stack Overflow
or by alamodey
Published on 2009-05-31T03:17:33Z
Indexed on
2010/03/23
11:03 UTC
Read the original article
Hit count: 211
I have this bit of code and I get an empty object.
@results = PollRoles.find(
:all,
:select => 'option_id, count(*) count',
:group => 'option_id',
:conditions => ["poll_id = ?", @poll.id])
Is this the correct way of writing the query? I want a collection of records that have an option id and the number of times that option id is found in the PollRoles model.
EDIT: This is how I''m iterating through the results:
<% @results.each do |result| %>
<% @option = Option.find_by_id(result.option_id) %>
<%= @option.question %> <%= result.count %>
<% end %>
© Stack Overflow or respective owner