1

Newbie and would really appreciate some help rendering objects in sets of 3's.

I currently display a list of objects with render:

<%= render @gifts %>

Each object has some characteristics that render from the partial _gift.html.erb

This all works fine. However, how do I loop through all the @gifts objects wrapping every 3 objects with a div? Desired result is something like:

<div class="row-fluid>
# The first 3 objects from @gifts
</div>

<div class="row-fluid>
# The next 3 objects from @gifts
</div>
Matt Wheeler
  • 197
  • 1
  • 2
  • 8

3 Answers3

3
<% @gifts.each_slice(3) do |slice| %>
  <div class="row-fluid>
    # slice now is a 3 element array, iterate over it and render as you see fit
  </div>
<% end %>

I'm more of a HAML guy, but this should work.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
0

each_slice is what you're looking for. It's covered in better detail here:

https://stackoverflow.com/a/2852103/9465

Community
  • 1
  • 1
jdl
  • 17,702
  • 4
  • 51
  • 54
0

Also consider in_groups_of (a Rails monkey-patch to Array):

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

MotownJoe
  • 78
  • 5