Reputation: 6180
I want to have a function to group users according to a certain age range. Then get their count which I can use to plot a bar-chart. e
this statement is able to plot a chart of their ages, but it is each users age. which is what i want to eliminate. if you would like to know am using chartkick to make the charts.
<%= bar_chart User.group("date_trunc('year', age(dob))").count, {library: {title: "User's Age"}} %>
I want the ages returned as:
<%= bar_chart [["Below 10", users_with_ages_lying_in this_range.count],
["10-19", users_with_ages_lying_in this_range.count],
["20-29", ],
["30-39", ],
["40-49", ],
["above 50",]], {library: {title: "User's Age"}}
%>
in short I would like this line of code User.group("date_trunc('year', age(dob))").count
to return only users for a given age range.
If you have any better ideas I would appreciate to know. I'm using postgres DB
Upvotes: 0
Views: 450
Reputation: 2141
I had a similar need to find events within a range.
I made a class method on a model:
def self.in_range(start_range, end_range)
where "((start_date <= ?) and (end_date >= ?))", end_range, start_range
end
which is used like so:
events.in_range(start_range, end_range).order('start_date ASC')
I am sure a similar one could be created using age instead of start_date and end_date.
Upvotes: 1