A non-weird replacement for grouped_collection_select

Updated . Posted . Visible to the public.

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

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
Profile picture of Henning Koch
Henning Koch
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-06-16 14:07)