In Groups Of in Rails 5

Steps

Step 1

List all the tasks in tasks index page.

<h1>Tasks</h1>
<table>
  <thead>
    <tr> <th></th> </tr>
  </thead>
  <tbody>
    <% @tasks.each do |task| %>
      <tr>
        <td>
          <%= task.name %> in <%= task.project.name %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

Step 2

We want to list 4 tasks in each row. Let's define rows and columns in view. Add in_groups_of method in tasks/index.html.erb:

<% @tasks.in_groups_of(4) do |row| %>
  <tr>
    <% for task in row %>
        <td><%= task.name %></td>
    <% end %>  
  </tr>
<% end %>

We get the error:

undefined method `name' for nil:NilClass

Step 3

We can fix this problem by not filling the array with nil values if they are not evenly divisible. Pass the false flag as the second argument to the in_groups_of method.

<h1>Tasks</h1>
<table>
  <thead>
    <tr>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <% @tasks.in_groups_of(4, false) do |row| %>
      <tr>
        <% for task in row %>
            <td><%= task.name %></td>
        <% end %>  
      </tr>
    <% end %>
  </tbody>
</table>

Reload the page. You will now see the tasks displayed in groups of 4.

Summary

In this article, you learned how to use in_groups_of to display tasks in a four column per row format.


Related Articles


Create your own user feedback survey