views:

65

answers:

1

Hello all.

I'm writing a reports dashboard for a rails app. The dashboard is for user data, and currently it's running multiple count an select queries to build the four or five reports on the page. I'm sure that there is a more efficient way to do this. How would I go about structuring the controller method so that it only runs one query, and then parses/subdivides the subsets needed for the individual reports?

For example, a user has a gender, an age, and an income range. Instead of doing

@men = User.count(:conditions => ['gender = ?', 'm']
@women = User.count(:conditions => ['gender = ?', 'f']
@age = User.count(:conditions => ['age_range = ?', 1]
etc.

Could I just do a single

User.find(:all, :select => 'id,gender,age_range,income_range')

And then parse out what I need?

Any help is appreciated.

Thank you.

+1  A: 

I believe you can do this

@users = User.all

@men = @users.select{|u| u.gender == 'm'}.size
@women = @users.select{|u| u.gender == 'f'}.size
@age = @users.select{|u| u.age_range == 1}.size
j.
Thank you, that worked perfectly. Just so I can break it down for myself, could you explain the syntax a bit? I'm still a little muddy when it comes to blocks in ruby.Thanks
Kevin Whitaker
I'm just iterating through all the users and performing my logic on each one. If true is returned, the user is included in the new array that will be returned when the iteration is finished. Sorry for my bad English and explanation. This post may help you: http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/
j.