如何创建按父分组的子模型记录的下拉列表 [英] How to create dropdown list of child model records grouped by the parent
问题描述
我有三个模型:属性,城市和区域。一个城市属于一个地区,而一个地区则有许多城市。用户在定义新属性时选择一个城市。
I have three models, Properties, Cities and Regions. A city belongs_to a region and region has_many cities. The user picks a city when defining a new property.
有很多城市,因此我希望下拉列表如下所示:
There are many cities so I'd like to have the dropdown list look something like this:
Region 1:
City 1
City 2
City 3
Region 2:
City 4
City 5
等。但是只有城市是可以选择的,即区域是灰色的,并且仅作为视觉引导。有没有一种方法可以按父分组子记录?
etc. But only the cities are selectable, ie the regions are greyed out and are only there as a visual guide. Is there a way to group the child records by parent?
推荐答案
您要使用rails option_groups_from_collection_for_select帮助器
You want to use the rails "option_groups_from_collection_for_select" helper
= option_groups_from_collection_for_select(@regions, :cities, :name, :id, :name, 3)
如果您要手动提供2级选项数组,则使用 grouped_options_for_select
if you want to manually provide the 2 level array of options, then use "grouped_options_for_select"
这篇关于如何创建按父分组的子模型记录的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!