Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

ruby - Grouped Select in Rails

Simple question really - how do I use the select(ActionView::Helpers::FormOptionsHelper) with grouped options?

I have got it working with a select_tag (ActionView::Helpers::FormTagHelper) but I would really like to have it using a select tag to match the rest of the form. Is this possible?

My options look like this:

[
  ['Group 1', ["Item 1", "Item 2", "Item 3"]],
  ['Group 2',["Item 1", "Item 2", "Item 3", "Item 4"]]
]

whilst my view is currently:

%tr#expense
  %td
    = f.text_field :value
    = f.hidden_field :type, :value => mode
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit

Correction, since you're using Arrays you'll need grouped_options_for_select

Example:

grouped_options = [
  ['Group 1',
    ["Item 1", "Item 2", "Item 3"]],
  ['Group 2',
    ["Item 1", "Item 2", "Item 3", "Item 4"]]
]
grouped_options_for_select(grouped_options)

Prints the following:

<optgroup label="Group 1">
  <option value="Item 1">Item 1</option>
  <option value="Item 2">Item 2</option>
  <option value="Item 3">Item 3</option>
</optgroup>
<optgroup label="Group 2">
  <option value="Item 1">Item 1</option>
  <option value="Item 2">Item 2</option>
  <option value="Item 3">Item 3</option>
  <option value="Item 4">Item 4</option>
</optgroup>

Note that you have to provide your own select tags to wrap this. There is no select function that will do grouping for you, just this method.

You should get over your reticence. The Rails Way (tm) to do what you ask is to use select_tag with grouped_options_for_select:

<%= select_tag "foo[bar]", 
grouped_options_for_select(@bars) %>

This is what happens when you go off the beaten path with Rails. :)

Here's a reference I just found on google:

http://www.ruby-forum.com/topic/185407


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...