Ruby Rails

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

14 Sep 2015
1 minute 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

How to

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


@accounts_alphabetical = Account.order(:name)
  .collect{ |account| [,] }
  .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.


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