Read more

A non-weird replacement for grouped_collection_select

Henning Koch
June 16, 2015Software engineer at makandra GmbH

Rails comes with grouped_collection_select Show archive.org snapshot that appears to be useful, but isn't.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

As an alternative, consider the flat_grouped_collection_select found below. It takes a third argument that extracts the group from each element in the collection:

= form.flat_grouped_collection_select :user_id, users, :department, :id, :full_name

Here is the monkey-patch:

class ActionView::Helpers::FormBuilder

  def flat_grouped_collection_select(field, collection, group_label_method, value_method, label_method, options = {}, html_options = {})
    hash = collection.group_by(&group_label_method).collect_hash do |group_label, group_entries|
      list_of_pairs = group_entries.collect { |entry|
        [entry.send(label_method), entry.send(value_method).to_s]
      }
      [group_label, list_of_pairs]
    end
    options_options = options.slice(:prompt)
    selected_key = object.send(field).to_s
    select(field, @template.grouped_options_for_select(hash, selected_key, options_options), options, html_options)
  end

end
Posted by Henning Koch to makandra dev (2015-06-16 16:07)