Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 of the glossary terms under each letter rather than only the ones that begin with the letter.. I've tried a few things but I'm not sure how to select the right thing.

like image 658
Carla Dessi Avatar asked Mar 06 '14 16:03

Carla Dessi


2 Answers

You should be able to do everything with your @alpha instance variable, since you're 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
like image 174
CDub Avatar answered Oct 11 '22 15:10

CDub


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
like image 4
T J Avatar answered Oct 11 '22 15:10

T J