Posted over 3 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:

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

Here is the monkey-patch:

Copy
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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Henning Koch
Last edit:
over 1 year 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