Ruby on rails RubyonRails-添加按列分组的选择选项
假设我有一个表,有两个字段:“Type”和“Name” 有没有一种方法可以创建一个下拉列表,显示如下内容:Ruby on rails RubyonRails-添加按列分组的选择选项,ruby-on-rails,Ruby On Rails,假设我有一个表,有两个字段:“Type”和“Name” 有没有一种方法可以创建一个下拉列表,显示如下内容: Type A All of the db entries that have Type A Type B All of the db entries with Type B <select> <%= options_from_collection_for_select(@modeTypeA, 'id', 'name') %> </se
Type A
All of the db entries that have Type A
Type B
All of the db entries with Type B
<select>
<%= options_from_collection_for_select(@modeTypeA, 'id', 'name') %>
</select>
<select>
<%= options_from_collection_for_select(@modeTypeB, 'id', 'name') %>
</select>
我该怎么做?我一直在看分组集合集合集合,但是这些示例似乎只是基于db关联对选项进行分组。在这种情况下,我只使用一个表,而不是两个表。您可以使用:
options_from_collection_for_select(collection, value_method, text_method, selected = nil)
然后将两个实例变量(例如@modeTypeA=Model.where(键入:“A”))传递给视图以在集合中使用。因此,一种可能的实现方式如下:
Type A
All of the db entries that have Type A
Type B
All of the db entries with Type B
<select>
<%= options_from_collection_for_select(@modeTypeA, 'id', 'name') %>
</select>
<select>
<%= options_from_collection_for_select(@modeTypeB, 'id', 'name') %>
</select>
创建一个类方法。
因此,在这里使用option\u groups\u from\u collection\u for\u select
对您没有帮助。它希望您的选项组是一个模型,选项组是另一个模型
您需要的是grouped\u options\u for\u select
,并使用class方法生成所需的嵌套数组以满足其需求
继续你原来的问题,你会想在模型中添加如下内容:
def self.select_options_grouped_by_type
self.uniq.pluck(:type).sort.collect do |type|
[
type,
YourModel.where( type: type ).collect { |record| [ record.name, record.id ] }
]
end
end
这将得到一个嵌套数组,其外观如下所示:
[
[ "Type A", [
[ "Name 1", 1 ],
[ "Name 2", 2 ],
... ],
[ "Type B", [
[ "Name 3", 3 ],
[ "Name 4", 4 ],
... ],
]
...
]
然后,您只需将其输入到分组的\u选项\u中,以便选择:
<%= grouped_options_for_select( YourModel.select_options_grouped_by_source ) %>
一艘班轮:
希望这能帮助别人。我也有同样的问题。James的回答只是创建了两个select
下拉列表,但我认为您(和我)所追求的是一个optgroup
内部的select
,它是由同一模型的一列值分组的,而不是关联。运气好吗?啊。。。知道了。为自己和他人发布了答案。