Reputation: 4740
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 of 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?
Upvotes: 1
Views: 285
Reputation: 771
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
Upvotes: 3
Reputation: 14967
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 <%= %>
.
Upvotes: 1