Topic: count and display results

hi, i'm newbie for rails. i need to display the results from counting data in the tables.
when i test select syntax in mysql query browser, the result run correctly.
then i created method in model to count customers
   def self.count_customer
     return Customer.count_by_sql("select count(*) from customers, managers where   customers.manager_id = managers.id group by manager_id")       
   end

after that, i coded in view
   <%= Manager.count_customer %>

but my web application display the results only first record of the table and display the same result all managers. you know manager has many customers but i got all managers has the same customer amount.

i'm sure that i did somethings wrong.
how to fix that?

Last edited by maya (2006-11-29 14:25:49)

Re: count and display results

If you set up the associations correctly (manager has_many :customers), you should be able to do this:

<%= @manager.customers.size %>

Rails will automatically build the count query for you, so there's no need to do it yourself.

Railscasts - Free Ruby on Rails Screencasts

Re: count and display results

i set ...
class Customer < ActiveRecord::Base
     belongs_to :manager

class Manager < ActiveRecord::Base
     has_many :customers


but i got the error

You have a nil object when you didn't expect it!
The error occured while evaluating nil.customers

Extracted source (around line #30):   
   30:      <td>(<%= @manager.customers.size %>)</td>

why?

Last edited by maya (2006-11-29 15:11:36)

Re: count and display results

You would need to set the @manager instance variable in my example. This can be any variable with a Manager model in it. For example, you can loop through all managers and call it on each one:

<% for manager in @managers %>
  Customer Count: <%= manager.customers.size %>
<% end %>

Assuming you did a find and set the @managers instance variable here.

Railscasts - Free Ruby on Rails Screencasts

Re: count and display results

it's great ! but just have a little bit.
the results display...

manager#1 has/have 5  4  2 customer(s)
manager#2 has/have 5  4  2 customer(s)
manager#3 has/have 5  4  2 customer(s)

how to correct that?
ps. ryanb, thank you very for your help.

Re: count and display results

just did somethings wrong, now i fix that and the results display correctly.
thank you so much ryanb.