如何使用Rails 3将数据划分为列?

时间:2022-11-12 12:38:47

How can I display results from an object into columns like the following:

如何将对象的结果显示为如下所示的列:

<ul>
    <li><a href="#">Category name</a></li>
    <li><a href="#">Category name</a></li>
    <li><a href="#">Category name</a></li>
</ul>
<ul>
    <li><a href="#">Category name</a></li>
    <li><a href="#">Category name</a></li>
    <li><a href="#">Category name</a></li>
</ul>
<ul>
    <li><a href="#">Category name</a></li>
    <li><a href="#">Category name</a></li>
    <li><a href="#">Category name</a></li>
</ul>

Regardless of results returned to @categories = Category.all I want to divide them up into three columns like this. What's the best way programmatically to do it?

无论返回到@categories = Category的结果是什么。我想把它们分成三列。用编程方式做这件事最好的方法是什么?

2 个解决方案

#1


8  

each_slice method can help you

each_slice方法可以帮助您

%w(a s d f g h).each_slice(3) {|x| p x}
["a", "s", "d"]
["f", "g", "h"]

In HAML, you can handle it by this way

在HAML,你可以这样处理。

- cats = Array.new(3, [])
  = @categories.each_slice(3) do |category|
    - cats = cats.zip(category).map(&:flatten)
  - cats.each do |subcat|
    %ul
      - subcat.each do |l|
        %li
          %a{:href => "#"}
            = l

#2


8  

Rails has a dedicated way to do that using in_groups:

Rails有一种专用的方法来使用in_groups:

<% @categories.in_groups(3, false) do |group| %>
<ul>
  <% group.each do |category| %>
  <li><%= category.name %></li>
  <% end %>
</ul>
<% end %>

The second argument of in_groups (which is false in this case) means that this code won't produce empty list items if @categories.size isn't a multiple of 3.

in_groups(在本例中为false)的第二个参数表示,如果是@categories,则此代码不会生成空列表项。大小不是3的倍数。

#1


8  

each_slice method can help you

each_slice方法可以帮助您

%w(a s d f g h).each_slice(3) {|x| p x}
["a", "s", "d"]
["f", "g", "h"]

In HAML, you can handle it by this way

在HAML,你可以这样处理。

- cats = Array.new(3, [])
  = @categories.each_slice(3) do |category|
    - cats = cats.zip(category).map(&:flatten)
  - cats.each do |subcat|
    %ul
      - subcat.each do |l|
        %li
          %a{:href => "#"}
            = l

#2


8  

Rails has a dedicated way to do that using in_groups:

Rails有一种专用的方法来使用in_groups:

<% @categories.in_groups(3, false) do |group| %>
<ul>
  <% group.each do |category| %>
  <li><%= category.name %></li>
  <% end %>
</ul>
<% end %>

The second argument of in_groups (which is false in this case) means that this code won't produce empty list items if @categories.size isn't a multiple of 3.

in_groups(在本例中为false)的第二个参数表示,如果是@categories,则此代码不会生成空列表项。大小不是3的倍数。