按类别分组循环 - 轨道

时间:2014-07-15 11:43:30

标签: ruby-on-rails twitter-bootstrap loops carousel

我正在尝试创建一个循环,将类别中的卡组合在一起,然后为每个卡创建一个轮播,并将卡片(在该类别中)作为图像。

以下是我的尝试,内部循环有效,但它只显示一个旋转木马中的所有卡片。我无法弄清楚如何按类别分组。

<% @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"}... 

1 个答案:

答案 0 :(得分: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 }