I have this function in my User model that calculates the User ages
def get_age
now = Time.now.utc.to_date
now.year - dob.year - ((now.month > dob.mon
So for thousands of users I'd definitely do this in the database. While the labels will probably need some massaging, you can start with a query like this:
User.group("date_trunc('year', age(dob))").count
This will result in a hash with entries that look something like this:
{
"00:00:00" => 3,
"1 year" => 5,
"2 years" => 8,
...
}
You can then do relabelling and group the year results into bins (e.g. 10-20) as needed. I wouldn't try to do this all in one line in your view - I'd make this a method either on the model or on a dedicated query object.