Option 1: 在你的City
模型,添加一个默认范围指示按字母顺序返回城市:
# app/models/city.rb
default_scope :order => 'cities.name ASC'
收藏品City
默认情况下,对象将按名称字母顺序返回。
Option 2:定义一个命名范围 in your State
model以字母顺序返回城市作为关联State
object:
# app/models/state.rb
scope :cities_by_name, -> { cities.order(name: :asc) } # Rails 4
scope :cities_by_name, cities.order("name ASC") # Rails 3
然后,将您的范围查询传递给您的grouped_collection
helper:
f.grouped_collection_select :city_id, State.order(:name), :cities_by_name, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'}