Order alphabetically and group by first letter

I currently have the following code:

- @alpha = Glossary.find(:all, :order =>"title ASC").group_by{|u| u.title[0]}
- @glossary = Glossary.find(:all, :order =>"title ASC")

- @alpha.each do|a|

  %h1= a[0]

  - @glossary.each do |g|
    %p display stuff

This displays all the glossary terms under each letter, not just those starting with a letter. I tried several things, but I'm not sure how to choose the right one.

+4
source share
2 answers

You can do everything with an instance variable @alphasince you are using group_by:

- @alpha = Glossary.find(:all, :order =>"title ASC").group_by{|u| u.title[0]}

- @alpha.each do |alpha, glossary_array|
  %h1= alpha
  - glossary_array.each do |item|
    %p= item
+4
source

You're close I think you just want to do

- @alpha = Glossary.order("title ASC").group_by{|u| u.title[0]}
- @alpha.each do |letter, items|
  %h1= letter
  - items.each do |item|
    %p= item
+3
source

Source: https://habr.com/ru/post/1530454/


All Articles