Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails - Create a table dynamically for variable number of cells

I'm trying to display a objects in my model in the form of a table, but am having a hard time trying to create the rows and columns dynamically.

I have a model called Pictures and currently I'm displaying all of them in a looooong list.

<% for picture in @pictures %>
   <p><%= image_tag(picture.url) %></p>
<% end %>

How can I turn this into a table in the view with rails?

<table>
<tr>
<% for picture in @pictures %>   
     <td> 
        <%= image_tag(picture.url) %>
     </td>
** Here's where I'm confused..How can I write after 6 cells create a new row?? *****
<% end %>
</table>

So the question is really related to how to breakup this type of data within the view.

like image 669
ChrisWesAllen Avatar asked Jun 29 '11 21:06

ChrisWesAllen


2 Answers

Have a look at the enumerable method ".each_slice".

http://www.ruby-doc.org/core/classes/Enumerable.html#M001514

With it you can do something along the lines of:

<table>
  <% @pictures.each_slice(6) do |slice| %>   
    <tr>
      <% slice.each do |picture| %>
        <td> 
          <%= image_tag(picture.url) %>
        </td>
      <% end %>
    </tr>
  <% end %>
</table>

You may have to do some fiddling to populate the last row nicely, but that should get you on your way.

like image 135
Pavling Avatar answered Nov 12 '22 13:11

Pavling


I really dig the each_slice solution. Just thought I'd chime in if you wanted to have a non-tabular view, you could find out your max-width and max-height for your images and set a container around your photos and just use css to float them all together. Each row would contain however many would fit in your containing div.

view

<% for picture in @pictures %>
   <div class="photo">
     <%= image_tag(picture.url) %>
   </div>
   <div class="float_clear"></div>
<% end %>

css

.photo {height: 150px; width: 150px; float:left;margin:0 10px; 10px 0;}
.photo img{max-height: 150px; max-width: 150px;}
.float_clear{clear:both;}
like image 42
Chris Barretto Avatar answered Nov 12 '22 15:11

Chris Barretto