How to create dropdown list of child model records

2019-06-08 07:13发布

问题:

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?

回答1:

You want to use the rails "option_groups_from_collection_for_select" helper

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-option_groups_from_collection_for_select

= option_groups_from_collection_for_select(@regions, :cities, :name, :id, :name, 3)

if you want to manually provide the 2 level array of options, then use "grouped_options_for_select"

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-grouped_options_for_select