views:

55

answers:

3

What's the beste way to show a list with 20 images in rows of 5? Or, in other words, how do I clean up this ugly snippet?

<div class="row">
  <% @images.each_with_index do |image, index| %>
    <% if index != 0 && index % 5 == 0 %>
      </div><div class="row">
    <% end %>
    <%= image_tag image.url %>
  <% end %>
</div>
+2  A: 

You can use each_slice to loop through the images in rows of five images each:

<% @images.each_slice(5) do |row| %>
  <div class="row">
    <% row.each do |image| %>
      <%= image_tag image.url %>
    <% end %>
  </div>
<% end %>
Pär Wieslander
Cool, this is a much cleaner solution. Thanks Pär!
Cimm
A: 

Try this :limit to your query

@images  = Image.find_all(:limit => 5)

This will give @images olny 5 images , and u can add conditions too

You should not send 100 results to a @images and put only 5 images o the page ,,

send only 5 result to @images

Arpit Vaishnav
Thanks Arpit but I don't think this is the right solution. I didn't say I don't want to show only 5 images in the view - I want to show them all - but with some HTML around them. Maybe I wasn't clear enough but the "row div" is a carousel like JavaScript widget.
Cimm
+1  A: 

you can also use in_groups_of http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Grouping.html which also has other options.

Sniper
Thanks, this is indeed another way to solve this.
Cimm