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:

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 %>