开发者

How to isolate/retrieve/count a subset of returned records in Rails

开发者 https://www.devze.com 2023-01-05 18:56 出处:网络
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 pa

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号