Dynamically divide array in several columns
I'm working in Ruby on Rails 2.3.8 and I've got a collection of categories. So, I would like to list them in three columns per row, in groups of 10, and to have as many rows as needed. The ammount o开发者_运维问答f categories can change, so the functionality should be dynamic.
Is there a "rails way" to accomplish this? or which is the best way to do it?
Take a look at the following railscasts episode:
http://railscasts.com/episodes/28-in-groups-of
The "in_groups_of" method should be exactly what you require:
>> [1,2,3,4,5,6,7].in_groups_of(2, false)
=> [[1, 2], [3, 4], [5, 6], [7]]
The documentation for in_groups_of can be found at:
http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M001423&name=in_groups_of
Don't know if it is "rails way", but for sure it is "my way" ;)
# in controller
@categories = Category.all
# in view
<table>
<% @categories.each_with_index do |cat, index| %>
<%= "<tr>" if index % 30 == 0 %>
<%= "<td>" if index % 10 == 0 %>
<%= cat.name %>
<%= "</td>" if (index + 1) % 10 == 0 || index + 1 == @categories.size %>
<%= "</tr>" if (index + 1) % 30 == 0 || index + 1 == @categories.size %>
<% end %>
</table>
If you will switch to Rails 3, you have to add raw
before putting any HTML tag inside <%= %>
.
精彩评论