IMEOS
  1. Home
  2. Work
  3. Contact
  4. Blog

Im Obstgarten 7
8596 Scherzingen
Switzerland

+41 79 786 10 11
(CET/CEST, Mo-Fr, 09:00 - 18:00)
io@imeos.com

IMEOS on GitHub
RubyRails

Order select tag entries alphabetically and group by first letter in Rails

Sep 14, 2015
2 minutes read

Select tags with many options can soon get confusing. Sorting them alphabetically and grouping the entries by their first letter is an easy solution.

Rails select group_by alphabetically
Rails select group_by alphabetically

How to

Assuming you want to group and sort an Account model by its name attribute:

Controller

@accounts_alphabetical = Account.order(:name)
  .collect{ |account| [account.name, account.id] }
  .group_by{ |account| account.first[0,1].upcase }

The last line groups by each accounts .name (.first) starting letter ([0,1]) and only if its unique of course. So @accounts_alphabetically is a Hash where the keys are the letters which was grouped by and the values are Arrays that contain the Accounts IDs and names.

View

<%%= form_for @person do |f| %>
  <%%= f.select :id, grouped_options_for_select(@accounts_alphabetical), { include_blank: 'Choose Account:' } %>
  …
<%% end %>

  • Privacy
  • Imprint
IMEOS