2014-05-20 36 views
1

我無法弄清楚如何在視圖中混洗表值。在我看來,我有一張左右兩列的桌子,並且只想洗牌右列。Rails視圖:混洗表列

show.html.erb

<table> 
    <% @items.each do |item| %> 
    <tr> 
    <td><%= item.left %><td> 
    <td><%= item.right %><td> 
    </tr> 
    <% end %> 
</table> 

「左」 和 「右」 共享同樣的主數據庫中的ID。任何關於如何洗牌的建議?謝謝!

回答

1

您可以使用shuffle,做這樣

<% shuffled_items = @items.shuffle %> 
<% @items.each_with_index do |item, index| %> 
    <tr> 
    <td><%= item.left %><td> 
    <td><%= shuffled_items[index].right %><td> 
    </tr> 
<% end %> 

詳細閱讀本文檔http://ruby-doc.org/core-1.9.3/Array.html#method-i-shuffle

+1

喔使用它!甚至不知道這樣的東西exists.Very很好:) – Pavan

+1

,不會產生請求的輸出。你最後一行2 * n tds ... – xlembouras

+0

感謝您指出,我正在更新我的答案 – RSB

0

我認爲最簡單的方法是有2個陣列。

@items_left@items_right

如:

items = Item.a_scope 
@items_left = items 
@items_right = items.pluck(:right).shuffle #if you are on > rails 3.2 

# @items_left = items.pluck(:left) #if only that attribute is needed 

,所以你可以按如下

<table> 
    <% @items_left.each_with_index do |item, i| %> 
    <tr> 
     <td><%= item.left %><td> 
     <td><%= @items_right[i] %><td> 
    </tr> 
    <% end %> 
</table>