views:

626

answers:

2

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 %>
A: 

you want to use this function to do things like this
PollRoles.count(:all, :group => 'option_id') should return a hash mapping every option_id with the number of records that matched it

adi92
I changed it to this:@results = PollRoles.count(:all, :group => 'option_id', :conditions => ["poll_id = ?", @poll.id])but still get a nil result.
alamodey
im confused.. u say want 'a collection of records that have an option id', but ur condition is :conditions => ["poll_id = ?", @poll.id]).. are option id's and poll id's the same.. could you explain the structure of your db a little better
adi92
options are related to a poll. A poll has many options. So here I'm obviously trying to display the results for a certain poll.
alamodey
A: 

What do you get with this:

PollRoles.find(:all,:conditions=>["poll_id = ?",@poll.id]).collect{|p| p.option_id}

klochner
I get an empty result, nil.
alamodey
then you have no PollRoles with poll_id == @poll.id
klochner
OK I am getting results actually. But how do I iterate through them? See edited code.
alamodey
you shouldn't be searching in your view, you want to collect all the data in your controller: @results = PollRoles.count(:all, :group => 'option_id', :conditions => ["poll_id =?",@poll.id]).collect{|option_id,count| [Option.find(option_id),count]} then in your view: <% @results.each do |option,count| %> <%= option.question %> <%= count %> <% end %>
klochner