Gurmukh Singh Gurmukh Singh - 6 months ago 53
Ruby Question

create table rows of 4 in rails

I have these checkboxes, I'm trying to create rows of 4 checkboxes. At the moment it creates one row.

<table>
<%= f.collection_check_boxes :expertise_ids, Expertise.all, :id, :name do |b| %>
<td>
<label style="margin-left:5px; margin-right:15px;" class="checkbox-inline">
<%= b.check_box %>
<%= b.label %>
</label>
</td>
<% end %>
</table>


Iv have tried something like this:

<table>
<%= f.collection_check_boxes :expertise_ids, Expertise.all, :id, :name do |b| %>
<% tablerows = 0 %>
<td>
<label style="margin-left:5px; margin-right:15px;" class="checkbox-inline">
<%= b.check_box %>
<%= b.label %>
<% tablerows += 1 %>
<% break if tablerows == 3 %>
</label>
</td>
<% end %>
</table>


Im trying something like this to iterate over and every time is counts to 4 in trying to generate a new row, but I'm not sure how to complete this.

Answer

You can use in_groups_of:

<table>
  <% Expertise.all.in_groups_of(4, false) do |expertise_group| %>
    <tr><!-- a new row for each group of four -->
      <%= f.collection_check_boxes :expertise_ids, expertise_group, :id, :name do |b| %>
         <td><!-- each checkbox get a column on its own -->
           <label style="margin-left:5px; margin-right:15px;" class="checkbox-inline">
             <%= b.check_box %>
             <%= b.label %>
           </label>
        </td>
      <% end %>
    </tr>
  <% end %>
</table>