ruby-on-railsrubyruby-on-rails-4activerecordform-helpers

Setting up grouped options for the f.select form helper


I'm curious on how I would go about creating a dropdown menu with locations that are grouped into categories in my Rails app.

A previous suggestion is to try the f.select_tag with the grouped_options_for_select form helpers. This did work, but when the user on the front end chose a location, the request wasn't being passed to the controller and hence, the location string is not showing up on the location confirmation page...

Reading the docs, I'm to use the f.select form helper if I'm to do this with Models, but I'm curious to know if I can create grouped options with this form helper

Here's the code using the f.select_tag helper (in a slim template-view):

f.select_tag :location_id, grouped_options_for_select(grouped_locations_hash), { include_blank: true }, class: 'form-control'

Using the above helper, the user selection for location on the front end is not being passed to the controller.

Attempting with the f.select form helper,

f.select :location_id, options_from_collection_for_select(locations_array, :id, :name), { include_blank: true }, class: 'form-control'

...the user selection is being passed, but, the dropdown menu does not have the locations grouped into categories (which I would like).

Any suggestions and or references from the community??

Many thanks!


Solution

  • You can do it mapping the collection and then grouping it by a value in the array, for example

    <%= f.select(:location_id, grouped_options_for_select(Location.all.map{|l| [l.name, l.category_name, l.id]}.group_by { |c| c[1] }), {include_blank: "Select one..."}, {:class => 'grouped_select',id:"location_grouped"}) %>
    

    This will create the select, grouped by category_name.