Rails 中的分组选择 [英] Grouped Select in Rails
问题描述
真正的简单问题 - 如何使用带有分组选项的 select(ActionView::Helpers::FormOptionsHelper)?
我已经使用 select_tag (ActionView::Helpers::FormTagHelper) 让它工作,但我真的希望它使用 select 标签来匹配表单的其余部分.这可能吗?
我的选项如下:
<预><代码>[['组 1', ["项目 1", "项目 2", "项目 3"]],['第 2 组',[第 1 项"、第 2 项"、第 3 项"、第 4 项"]]]虽然我目前的观点是:
%tr#expense%td= f.text_field :值= f.hidden_field :type, :value =>模式
编辑
更正,因为您使用的是数组,所以您需要 grouped_options_for_select
示例:
grouped_options = [['第 1 组',[项目 1"、项目 2"、项目 3"]]、['第 2 组',[项目1"、项目2"、项目3"、项目4"]]]grouped_options_for_select(grouped_options)
打印以下内容:
请注意,您必须提供自己的 select 标签来包装它.没有 select 功能可以为您进行分组,只有这种方法.
你应该克服沉默.Rails Way (tm) 做你要求的是使用 select_tag 和 grouped_options_for_select:
<%= select_tag "foo[bar]",grouped_options_for_select(@bars) %>
这就是当你离开 Rails 时会发生的事情.:)
这是我刚刚在谷歌上找到的参考:
http://www.ruby-forum.com/topic/185407
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
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
这篇关于Rails 中的分组选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!