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.
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.
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;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With