Display associated record count

Hi all,

I have a website which has users and each user can creat multiple product records. I have the ability to show the associated records under the user profile but what I want to do now is on the user index, to display a number representing how many products that user has up for sale. So basically to count all the records for each user and display on the index so that it would look like the following e.g.

Username Favourite Console Games available to trade jimmypop01 Playstation 3 0 andypandy Playstation 3 3 GoogleMail Playstation 3 2

I was wondering if anyone knows how I would go about doing this.

All I have managed so far is to display how many records are in that table.

So that people know I have two separate tables for users and games.

Thanks Christopher Jones

I have a website which has users and each user can creat multiple product records. I have the ability to show the associated records under the user profile but what I want to do now is on the user index, to display a number representing how many products that user has up for sale. So basically to count all the records for each user and display on the index so that it would look like the following e.g.

Username Favourite Console Games available to trade jimmypop01 Playstation 3 0 andypandy Playstation 3 3 GoogleMail Playstation 3 2

I was wondering if anyone knows how I would go about doing this.

All I have managed so far is to display how many records are in that table.

So that people know I have two separate tables for users and games.

Not very efficient, but you could do:

@users.each do |user|   user.games.count end

Or in your controller you could do...

@game_counts = Game.count(:group => :user_id)

And then do the necessary lookup in the view to match them up.

Or you could add a "games_count" field to the user model and use the :counter_cache option on the relationship so you could do:

@users.each do |user|   user.games_count end

If you're going to be showing this a lot, I'd go with the latter.

-philip