Posted about 4 years ago. Visible to the public. Repeats.

A non-weird replacement for grouped_collection_select

Rails comes with grouped_collection_select 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

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Henning Koch
Last edit:
almost 2 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more