Pregunta

I have been searching in vain to accomplish the following in a more clean manner.

I have a hash of strings which I am calling from my controller:

@categories = Category.find

and I am trying to display the results in three separate unordered lists (ul).

The following is an ugly version of what I am trying to accomplish:

<div class="span-7">
    <ul>
    <% @categories.first(4).each do |category| %>

        <li><%= category.name %></li>

    <% end %>
    </ul>       
</div>

<div class="span-7">
    <ul>
    <% @categories[5..8].each do |category| %>

        <li><%= category.name %></li>

    <% end %>
    </ul>       
</div>

<div class="span-8 last">
    <ul>
    <% @categories[9..12].each do |category| %>

        <li><%= category.name %></li>

    <% end %>
    </ul>       
</div>

(Note: I am using BlueprintCSS, thus the excess of "span-x")

I think there is a cleaner way to do this using grouping (http://rails.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Grouping.html) but I can't figure out how to tie all of this together.

I'd really appreciate it if someone could point me in the right direction. Thank you.

(I am using Rails 3.0.11)

¿Fue útil?

Solución

You're on the right track. This should do what you want.

<% category_count = 0 %>
<% @categories.in_groups_of(4) do |group| %>
  <% category_count += group.size %>
  <div class="<%= category_count == @categories.size ? "span-8 last" : "span-7" %>">
    <ul>
    <% group.each do |category| %>
      <% if category %>
      <li><%= category.name %></li>
      <% end %>
    <% end %>
    </ul>       
  </div>
<% end %>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top