Grouped Collection选择按字母顺序排列的Rails

我终于想出了如何使用本教程实现动态选择菜单。

一切正常,但是如何按名称组织下拉列表中的城市….

以下是我写的所有代码。 (如果您需要任何进一步的信息,请告诉我)

新的铁路请帮助:)

VIEWS

 
"Select a State"}, {:class=>'dropdown'} %>
### I would like the order of the cities displayed in the drop down to be alphabetized
"Select a City"}, {:class=>'dropdown'} %>

选项1 :在您的City模型中,添加一个默认范围 ,指示按字母顺序返回城市:

 # app/models/city.rb default_scope :order => 'cities.name ASC' 

默认情况下, City对象的集合将按名称的字母顺序返回。

选项2State模型中定义一个命名范围 该范围按字母顺序返回城市作为State对象的关联:

 # 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帮助器:

 f.grouped_collection_select :city_id, State.order(:name), :cities_by_name, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'} 

使用Rails 4:

 # app/models/city.rb scope :ordered_name, -> { order(name: :asc) } # app/models/state.rb has_many :cities, -> { ordered_name } 

如何使用default_scope订购City模型?

或者像这样创建一个State范围:

 scope :ordered_cities, ->{ cities.order(:name) } 

而不是将您的选择更改为

 f.grouped_collection_select :city_id, State.order(:name), :ordered_cities, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'} 

像这个post中的其他人一样,我在使用范围时遇到了问题。 相反,我通过在State模型中添加另一个关联来使其在Rails 5中工作:

has_many :cities_by_name, -> { order(:name) }, class_name: 'City'