Andre Zimpel
Andre Zimpel

Reputation: 2343

Grouping in Rails with Group Headline

I'd like to group a collection alphabetically by title:

@projects = Project.find_all_by_user_id(current_user.id)

The view should contain a list of projects grouped by title, e.g.:

A
Andre's Project
Ananas

C
Chemnitz
Cleopatra

F
Find a new office

S
Super secret stuff

But I got no clue how to do this in rails. Does rails provide a functionality to do this or do I need to write my own loop looking for the titles etc.?

Thank you!

Upvotes: 0

Views: 106

Answers (1)

mttmzr
mttmzr

Reputation: 198

Not Rails but Ruby does the trick. In your view:

<% @projects.group_by{ |project| project.name[0].downcase }.each do |letter, projects| %>
  <div id="letter-<%= letter %>" class="letter-group">
    <h2><%= letter.upcase %><h2>
    <% projects.each do |project| %>
      <p><%= link_to project.name, project %></p>
    <% end %>
  </div>
<% end %>

group_by (ruby-doc) returns a hash you can easily loop through with letters as keys and arrays of corresponding projects as values. Be sure to already get your records sorted by project's name: (in your controller)

@projects = Project.order("name ASC").find_all_by_user_id(current_user.id)

Upvotes: 3

Related Questions