2014-07-15 27 views
0

我試圖創建一個循環,將組一起在由類別陣列的卡,然後創建一個轉盤爲每一個,與所述卡(該類別)作爲圖像。組按類別環 - 導軌

下面是我的嘗試,內部循環工作,但它只顯示了一個輪播中的所有卡片。我不知道如何使它按類別組..

<% @cards.group_by(:categories).each do |c| %> 

    <h2><%= c["categories"] %></h2> 

    <div id="myCarousel" class="carousel slide" data-interval="false"> 

     <!-- Carousel items --> 
     <div class="carousel-inner"> 
      <div class="item active"> 
       <div> 

        <% @cards.each_with_index do |p, i| %> 

        <div class="span3"> 

         <a href="#"><img src=<%= p["url"] %> alt="" class="img-responsive"></a> 

        </div> 
        <% if ((i+1) % 4) == 0 %> 

       </div> 
       <!--/row--> 
      </div> 
      <!--/item--> 
      <div class="item"> 
       <div> 

        <%end%> 
        <%end%> 

       </div> 
       <!--/carousel-inner--> 

       </div> 
       <!--/myCarousel--> 

      </div> 
      <a class="left carousel-control" href="#myCarousel" data-slide="prev">‹</a> 

      <a class="right carousel-control" href="#myCarousel" data-slide="next">›</a> 

     </div> 
     <%end%> 

數組:

@cards = [{"url"=>"BB08-74C2-6C06-43CD-385B.jpg", "categories"=>"Birthday", "desc"=>"9 - Orange/Purple Dotty"}... 

回答

0

你幾乎沒有!

下面是group_by使用正確的語法:

<% @cards.group_by { |card| card['categories'] }.each do |category, cards| %> 
    <h2><%= category %></h2> 
    # etc. 

    <% cards.each_with_index do |p, i| %> 
    # your view to display each card 
    <% end %> 

    # etc. 
<% end %> 

group_by()方法將組由塊返回的每個uniq的對象上的陣列你給它,例子:

['Alice', 'John', 'Alex'].group_by do |element| 
    element[0] # returns the first letter of the string 
end 
# returns 
{ 'A' => ['Alice', 'Alex'], 
    'J' => ['John'] } 

# this instruction 
@cards.group_by(&:category) 
# is a shorthand for the long-version 
@cards.group_by { |card| card.category } 
+0

我在第一行得到'undefined method'categories'' –

+0

爲什麼在我的建議代碼中只使用'category'時,爲什麼要使用名爲'categories'的變量?您應該能夠自己找到錯誤並輕鬆識別它。這是一個語法錯誤@CarlaDessi – MrYoshiji

+0

對不起,我的問題出現了一個錯字,我更新了它並更改了您提供的匹配代碼,這就是我得到的錯誤 –