making a pie-chart of the user age in rails

2019-03-04 02:09发布

问题:

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.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end

I want a rails statement that yields a query against the users using this function and returns their age numbers. Then the ages are grouped in labels such as [below 10, between 10-20, etc]

something like:

<%= pie_chart User.group("get_age"), {library: {title: "User's Age"}} %>

where get_age is the function written in users model. Note: even when I define the function as self.get_age still it is not working

回答1:

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.