esafwan
esafwan

Reputation: 18009

Number the result of views in Ruby on Rails

I am getting data in from a controller and its printed through a loop. This is the example from the getting started guide. I want each row to have class in numbered in order like, class-1 class-2 etc. Below is my code in view file.

<% @posts.each do |post| %>
  <tr>
    <td><%= post.title %></td>
    <td><%= post.text %></td>
    <td><%= link_to 'Show', post_path(post) %> | </td>
    <td><%= link_to 'Edit', edit_post_path(post) %> | </td>
    <td><%= link_to 'Delete', post_path(post),
                    method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

For example each row should be having classes in order like below when rendered:

  <tr class="class-1">
    <td>title</td>
  </tr>
  <tr class="class-2">
    <td>title</td>
  </tr>
  <tr class="class-3">
    <td>title</td>
  </tr>

Upvotes: 0

Views: 56

Answers (1)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Something like

<% classid = 0 %>
<% @posts.each do |post| %>
  <%= "<tr class=\"class-#{classid}\">" %>  
    <td><%= post.title %></td>
    <td><%= post.text %></td>
    <td><%= link_to 'Show', post_path(post) %> | </td>
    <td><%= link_to 'Edit', edit_post_path(post) %> | </td>
    <td><%= link_to 'Delete', post_path(post),
                    method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
  <% classid +=1 %>
<% end %>

That said I'd be looking at presenter pattern, or a method on whatever class post is or better still if post is in the db, using it's id instead of sequential number.

Upvotes: 1

Related Questions