making a pie-chart of the user age in rails

后端 未结 1 618
囚心锁ツ
囚心锁ツ 2021-01-28 16:41

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         


        
相关标签:
1条回答
  • 2021-01-28 17:09

    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.

    0 讨论(0)
提交回复
热议问题