Good afternoon. I am new to ruby and trying to build my first application. I am using sqlite database and rails 5.0. I have a model called Person that has the first name, last name and date of birth as attributes. On the page where I list people I want to add the age of the people and obtain an average of the ages of the people
My controller looks like this:
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
And my view like this
<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>
Since I don't have a field in the database called "age" I can't understand how I can achieve the result. The objective would be to iterate through each of the people and divide it by the length of it, or is there an easier way?
Please excuse my ignorance, thank you very much in advance.