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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)