Luka Kerr Luka Kerr - 4 months ago 9
Ruby Question

Create new tablerow for every 8 entrys Rails

I have documents that are uploaded to my site, and these are stored in a database. I want to make it so that every 8 documents uploaded, a new row in a table is created so that when a new document is uploaded, if there are already 8 documents in the table row, that document will be placed in a new row.

Currently I have it so that every time a document is added, a new table cell is created with the new document and its title inside. I just don't know how to make it so that after 8 documents instead of creating one very long table, a new table row is created to accomodate the new documents.

Below is my code and ruby loop for the table:

<table>
<% @documents.each_slice(8) do |document| %>
<tr>
<% document.each do |document| %>
<td><%= document.title %>: <%= link_to "Download", Document.last.pdf.url(:original, false) %>
</td>
</tr>
</table>
<% end %>
<% end %>


And below is the outcome:

enter image description here

As you can see, I have created more than 8 documents, but they are not creating a new table row. Open to suggestions!

Answer

Your code is almost right, except the facts that you have used the same document block argument in two different do blocks like here:

<table>
<% @documents.each_slice(8) do |document| %>
<tr>
  <% document.each do |document| %>

as well as the end statements have been used in a messy way.


Use this code snippet: Hope it works!

<table>
<% @documents.each_slice(8) do |eight_documents| %>
  <tr>
  <% eight_documents.each do |document| %>
    <td><%= document.title %>: <%= link_to "Download", Document.last.pdf.url(:original, false) %></td>
  <% end %>
  </tr>
<% end %>
</table>