How to create a grouped select box using simple_form?
If you hava two models which are category, subcategory as follows:
class Category < ActiveRecord::Base
has_many :products
has_many :subcategories
end
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
end
Then you can use
<%= simple_form_for [:admin, @yourmodel] do |f| %>
<%= f.input :subcategory_id, collection: Category.all, as: :grouped_select, group_method: :subcategories, prompt: "Select One" %>
<%= f.submit "Submit" %>
<% end %>
which result like this:
<div class="form-group grouped_select optional yourmodel_subcategory_id">
<label class="grouped_select optional control-label" for="yourmodel_subcategory_id">Subcategory</label>
<select class="grouped_select optional form-control" id="yourmodel_subcategory_id" name="yourmodel[subcategory_id]">
<option value="">Select One</option>
<optgroup label="Your 1st Category">
<option value="This subcategory id">one subcategory belongs to Your 1st Category</option>
</optgroup>
<optgroup label="Your 2nd Category">
<option value="This subcategory id">one subcategory belongs to Your 2nd Category</option>
</optgroup>
</select>
</div>
Hope this helps.
The question is old but it's the top result for "simple_form grouped select" google search anyway so I figured the next reader might benefit from a few creative ways to create these with the latest simple_form (taken from tests, which are always the best documentation indeed)
<%= f.input :author,
:as => :grouped_select,
:collection => [['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]],
:group_method => :last %>
<%= f.input :author,
:as => :grouped_select,
:collection => Proc.new { [['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]] },
:group_method => :last %>
<%= f.input :author,
:as => :grouped_select,
:collection => { ['Jose', 'Carlos'] => 'Authors' },
:group_method => :first,
:group_label_method => :last %>
<%= f.input :author,
:as => :grouped_select,
:collection => { 'Authors' => ['Jose', 'Carlos'] },
:group_method => :last,
:label_method => :upcase,
:value_method => :downcase %>