Display chronological order of number of records

2019-08-30 09:51发布

问题:

In rails when displaying a list of table records, I have a column which displays the id of each record (so as to see how many records exist in the table) The only problem is for example is if record number 3 is deleted, then the id is also removed (due to uniqueness).

Instead of displaying the id, is there a way I can list 1,2,3,4,5 etc when viewing the list? in a table?

This is my table :

  <center>
  <p class="recordnumber"><%= pluralize(@ranches.size, 'Ranch') %> found<p>

  <%= render :partial => "shared/newlink" %>

  <table class="listing" summary="Ranches">
   <tr>
    <th>#</th>
    <th>Ranch Name</th>
    <th>Address</th>
    <th>Telephone</th>
    <th>Actions</th>
   </tr>
   <% @ranches.each do |ranch| %>
   <tr class="<%= cycle('odd', 'even') %>">
    <td><%= ranch.id %></td>
    <td><%= ranch.name %></td>
    <td><%= ranch.address_line_1 %>,</br><%= ranch.town_city %>,</br><%= ranch.postcode %></td>
    <td><%= ranch.telephone %></td>
    <td>
     <%= link_to("Edit", {:action => 'edit', :id => ranch.id}, :class => 'buttons') %>
     <%= link_to("Delete", {:action => 'delete', :id => ranch.id}, :class => 'buttons') %>
    </td>
    </tr>
   <% end %>
  </table>

回答1:

Yes. Replace each with each_with_index like this:

<% @ranches.each_with_index do |ranch, i| %>
   <tr class="<%= cycle('odd', 'even') %>">
    <td><%= i + 1 %></td>
    <td><%= ranch.name %></td>
....

The i + 1 is there because each_with_index starts at zero.