在rails中创建用户年龄的饼图 [英] making a pie-chart of the user age in rails

查看:173
本文介绍了在rails中创建用户年龄的饼图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的用户模型中有这个函数来计算用户年龄

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



我想要一个rails语句,查询针对使用此函数的用户,并返回其年龄数字。
然后年龄分组在诸如[10以下,10-20之间等]的标签中。

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]

如下:

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

其中get_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

推荐答案

即使我将函数定义为self.get_age也不起作用

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

看起来像这样:

{
   "00:00:00" => 3,
   "1 year" => 5,
   "2 years" => 8,
   ...
}

根据需要将年度结果转换为箱(例如10-20)。我不会尝试在你的视图中在一行中做这一切 - 我会使这个方法在模型上或一个专用的查询对象。

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.

这篇关于在rails中创建用户年龄的饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆