How to isolate/retrieve/count a subset of returned records in Rails
-
01-10-2019 - |
Question
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.
Solution
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow