2011-06-29 47 views
6

我試圖以表格的形式在我的模型中顯示對象,但我很難嘗試動態創建行和列。Ruby/Rails - 爲可變數量的單元格動態創建表格

我有一個名爲Pictures的模型,目前我在looooong列表中顯示所有模型。

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

我怎樣才能把它變成一個表中的軌道與視圖?

<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> 

所以這個問題真的與如何在視圖內分解這種類型的數據有關。

回答

11

看看枚舉方法「.each_slice」。

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

有了它,你可以做線沿線的東西:

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

您可能必須做一些擺弄很好地填充了最後一排,而是應該讓你對你的方式。

+1

我知道的Ruby/Rails不得不沿着這些路線的東西。儘管如此,我還沒有這樣做,所以從未做過這方面的研究。 –

+0

這看起來比我的答案更好!更可讀。 – drummondj

0

我在軌道上肯定紅寶石有一些這方面的幫手 - 但如果沒有,這裏是我如何在我過去的生活走近這種佈局的一個低級別的PHP開發者:

保持計數,模6(即i =(i + 1)%6)。如果i == 0,則輸出< tr> </tr>。

所以,像這樣:

<% i = 0 %> 
<tr> 
    <% 
    @pictures.each do |picture| 
     i = (i + 1) % 6 
    %> 
    <%= '<tr></tr>' if i == 0 %> 
    <td> 
     <%= image_tag(picture.url) %> 
    </td> 
    <% end %> 
</tr> 
+0

如果您使用此方法,而不是設置「我」,您可以使用each_with_index方法。 – Pavling

0

我會使用%(模數),像這樣:

<table> 
    <% rows = 0 %> 
    <% @pictures.each do |picture| %> 
    <%= "<tr>" if rows % 6 %> 
    <td><%= image_tag(picture.url) %></td> 
    <% rows += 1 %> 
    <%= "</tr>" if rows % 6 %> 
    <% end %> 
    <%= "</tr>" unless rows % 6 %> 
</table> 
1

我真的挖each_slice解決方案。如果你想擁有非表格式的視圖,只要想一想就知道,你可以找到你的圖片的最大寬度和最大高度,並在你的照片周圍設置一個容器,然後用css將它們全部浮起來。每行都會包含很多適合您的包含div。

視圖

<% 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;} 
+1

我同意,這不回答問的問題。但可能提供的解決方案在HTML和響應式佈局方面最爲正確。如果還有其他選項,表格不應該用於佈局 – jonas

+0

謝謝@jonas!我確信有很多不同的方法可以做到這一點,同時遵循最佳做法,因爲網頁瀏覽對移動設備的要求更高。 –

0

這樣在軌的另一個好方法是使用方法in_groups_of

所以你可以有

<table> 
    <% @pictures.in_groups_of(6, false) do |group| %> 
    <tr> 
     <% group.each do |picture| %> 
     <td> 
      <%= image_tag(picture.url) %> 
     </td> 
     <% end %> 
    </tr> 
    <% end %> 
</table> 

下面是該方法的文檔:http://apidock.com/rails/Array/in_groups_of