简体   繁体   English

Rails:从出生日期起从 model 的所有实例中获取平均值

[英]Rails: getting an average from all the instances of a model from birthdate

Im kinda new to the dev world and have the next issue:我对开发世界有点陌生,并且有下一个问题:

I need to display the average age from a group of people.我需要显示一组人的平均年龄。 Since i cannot have an "age" property in the model, i defined the age method on the class as follows:由于我在 model 中不能有“年龄”属性,因此我在 class 上定义了年龄方法,如下所示:

class Persona < ApplicationRecord


require 'date'
    def age
      now = Time.now.utc.to_date
      dob = self.fecha_de_nacimiento
      now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
    end
end

This is my controller:这是我的 controller:

 def index
@personas = Persona.order(Arel.sql("cast(strftime('%m', fecha_de_nacimiento) as integer)"))

This is because I need to have the table ordered by month of birth on the index view.这是因为我需要在索引视图上按出生月份排序表。

Now I need to show the average age of Persona, but have tried with persona.average(age), persona.average(:age) and so on and cant seem to get it to work.现在我需要显示 Persona 的平均年龄,但我尝试过使用 persona.average(age)、persona.average(:age) 等等,但似乎无法让它发挥作用。 Is there a way to do it with average or to make the sum of all ages and then divide it by the total number of my persona instances?有没有办法用平均值或所有年龄的总和然后除以我的角色实例的总数?

Thanks in advance to anyone who might help me.提前感谢任何可能帮助我的人。

Just found the way to make it work, If anyone needs it.刚刚找到使它工作的方法,如果有人需要它。 what I did was just sum all the ages and then divide it by @personas:lenght in my view with embedded ruby like this:我所做的只是将所有年龄相加,然后将其除以@personas:lenght,在我看来,嵌入式 ruby 如下所示:

<p>


El promedio de edad es:
  <%= @personas.sum(&:age) / @personas.length %>
</p>

And it worked fine just like that!它就像那样工作得很好!

This older answer really helped.这个较旧的答案确实有帮助。 Rails 4 Sum by Model Method Rails 4 通过 Model 方法求和

Hope this helps anyone else!希望这对其他人有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM