繁体   English   中英

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

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

我对开发世界有点陌生,并且有下一个问题:

我需要显示一组人的平均年龄。 由于我在 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

这是我的 controller:

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

这是因为我需要在索引视图上按出生月份排序表。

现在我需要显示 Persona 的平均年龄,但我尝试过使用 persona.average(age)、persona.average(:age) 等等,但似乎无法让它发挥作用。 有没有办法用平均值或所有年龄的总和然后除以我的角色实例的总数?

提前感谢任何可能帮助我的人。

刚刚找到使它工作的方法,如果有人需要它。 我所做的只是将所有年龄相加,然后将其除以@personas:lenght,在我看来,嵌入式 ruby 如下所示:

<p>


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

它就像那样工作得很好!

这个较旧的答案确实有帮助。 Rails 4 通过 Model 方法求和

希望这对其他人有帮助!

暂无
暂无

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

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