Create a new Bootstrap row every third array element

I have a @schools array (School.all) and I am showing these @schools in Bootstrap row (3 per row). I was wondering how I can do this so that for every third element in @schools Ruby / Rails will create a new line and then repeat the process. Thank.

<% for 3 in @schools %>
  <div class="row">
    <% @schools.each do |s| %>
      <div class="col-md-4">
      </div>
    <% end %>
  </div>
<% end %>

      

+3


source to share


2 answers


each_slice

is your friend.



<% @schools.each_slice(3) do |schools| %>
  <div class="row">
    <% schools.each do |s| %>
      <div class="col-md-4">
      </div>
    <% end %>
  </div>
<% end %>

      

+8


source


<% @schools.in_groups_of(3) do |schools| %>
  <div class="row">
    <% schools.each do |s| %>
      <div class="col-md-4">
      </div>
    <% end %>
  </div>
<% end %>

      



For documentation: http://apidock.com/rails/Array/in_groups_of

+2


source







All Articles