[英]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.