Jean-Baptiste
Jean-Baptiste

Reputation: 29

Sort alphabetically and group by first letter

I'm currently doing a dictionnay, glossary here http://beta.emangaka.com/definitions

I sort the definition alphabetically.

definitions_controller.rb :

  def index
    @definitions = Definition.all.order('title ASC')
    @titre = "Définitions"
  end

index.html.erb

<% @definitions.each do |definition| %>
...

The list is too long and I'm looking for group by letter too always based on the first letter of "title".

How to do ? Merci. Thank you.

Upvotes: 2

Views: 856

Answers (1)

Pavan
Pavan

Reputation: 33542

You can use group_by like below

@definitions = Definition.all.order('title ASC').group_by{|d| d.title[0]}

And in the view

<% @definitions.each do |letter, definition| %>
  <h2><%= letter %></h2>
  <% definition.each do |defn| %>
    <%= defn %>
  <% end %>
<% end %>

Upvotes: 3

Related Questions