【发布时间】:2021-08-27 22:13:45
【问题描述】:
下午好。我是 ruby 新手,正在尝试构建我的第一个应用程序。 我正在使用 sqlite 数据库和 rails 5.0。 我有一个名为 Person 的模型,它具有名字、姓氏和出生日期作为属性。 在我列出人员的页面上,我要添加人员的年龄并获取人员的平均年龄
我的控制器如下所示:
before_action :set_persona, only: %i[ show edit update destroy ]
# GET /personas or /personas.json
def index
@persona = Persona.order("cast(strftime('%m', fecha_nacimiento) as integer)")
end
我的看法是这样的
<table>
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
<th>Fecha nacimiento</th>
<th>Dni</th>
<th>Edad</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @persona.each do |persona| %>
<tr>
<td><%= persona.nombre %></td>
<td><%= persona.apellido %></td>
<td><%= persona.fecha_nacimiento %></td>
<td><%= persona.dni %></td>
<td><%= Time.now.year - persona.fecha_nacimiento.year %></td>
<td><%= link_to 'Detail', persona %></td>
<td><%= link_to 'Edit', edit_persona_path(persona) %></td>
</tr>
<% end %>
</tbody>
</table>
<p>El promedio de edad de las personas es: </p>
由于我在数据库中没有名为“年龄”的字段,我无法理解如何获得结果。 目标是遍历每个人并将其除以长度,还是有更简单的方法?
请原谅我的无知,非常感谢您。
【问题讨论】:
标签: ruby-on-rails