在Rails视图中,如何迭代一组应该显示为4行的对象?

时间:2013-08-02 01:41:52

标签: ruby ruby-on-rails-3

现在我正在使用模数运算符并执行以下操作: 目的只是关闭前一个并在数组/结果中的每四个项后创建一个新的“row-fluid”div

<div class="row-fluid">
  <% Group.all.each_with_index do |g, index| %>
    <% if index != 0 && index % 4 == 0 %> </div> <br> <div class="row-fluid"> <% end %>
    <div class="col-lg-3" id="my_group_tile_<%= g.id %>">
      <div class="tiletop">
        <div class="span12">
         <%= cl_image_tag(g.avatar, :crop => :pad, :height => 200, :width => 250, :class => "tile-image") %>
         </div>
        <h4 id="tileheader"> 
          <a href="/groups/<%= g.id %>"><%= g.title %> &nbsp; </a>  
        </h4>
      </div>
    <div class="tile-info">
      <%= truncate(g.info, :length => 100, :omission => '... (continued)') %>
    </div>    
    <hr>
    <span id="group_members_count_<%= g.id %>">    
      <span class="badge badge-black" style="color:white">
        <%= g.members.count %> members
      </span> 
    </span>
    <span id="join_<%= g.id %>" class="btn-wrapper">
      <%= render :partial => 'join_button', :locals => { :group => g } %>
    </span>
  </div>
  <% end %>
</div>

更新:使用接受的答案后,事情会更加清晰。

<% Group.all.each_slice(4) do |slice_of_four| %>
  <div class="row">
    <div class="bs-example">
      <div class="row">
        <% slice_of_four.each do |g| %>
          <div class="col-lg-3" id="my_group_tile_<%= g.id %>">
            <a href="#" class="thumbnail">
              <%= cl_image_tag(g.avatar, :crop => :pad, :height => 180, :width => 266, :class => "tile-image") %>
            </a>
          </div>
        <% end %>
      </div>
    </div>
  </div>  
<% end %>

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以尝试使用each_slice枚举器 http://apidock.com/ruby/Enumerable/each_slice

Group.all.each_slice(4) do |slice_of_four|
   *now you can do your operations on the slices of four*
end 

并尝试不使用Group.all它将获取内存中的所有组,如果groups表很大,则会出现不必要的问题