making a pie-chart of the user age in rails

元气小坏坏 提交于 2019-12-02 17:50:59

问题


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.



来源:https://stackoverflow.com/questions/19797869/making-a-pie-chart-of-the-user-age-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!