Ashley Bye
Ashley Bye

Reputation: 1750

Rails group_by and in_groups_of error

I have a list of organisations, grouped and displayed by their name, in alphabetical order. I want to display these across 4 columns for each letter, i.e.:

A
A... A... A... A...
A... A... A... A...

...

Z
Z... Z... 

I have used the following code:

<% @organisations.keys.sort.each do |starting_letter| %>
    <div class="page-chunk default">
        <h6><%= starting_letter %></h6>
        <% @organisations[starting_letter].each do |organisations| %>
            <% organisations.in_groups_of(4).each do |column| %>
                <div class="one_quarter">
                    <% column.each do |organisation| %>
                        <%= link_to organisation.name, organisation_path(organisation) %><br />
                    <% end %>
                </div>
            <% end %>
        <% end %>
    </div>
<% end %>

And in the controller:

@organisations = Organisation.all.group_by{ |org| org.name[0] }

But get undefined methodin_groups_of' for #for my troubles. If I change the code to@organisations[starting_letter].in_groups_of(4).each do |organisations|then I get aNilClass` error.

What have I done wrong and how should I fix it?

Upvotes: 1

Views: 1145

Answers (1)

johnnycakes
johnnycakes

Reputation: 2450

Try organisations.in_groups_of(4, false) Without the false, it will fill in any empty spots in the last group with nils, which means it will try to call name on nil.

Upvotes: 6

Related Questions