4

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

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

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

Rails 新手请帮忙:)

意见

<%= simple_form_for ([@book, @rating]) do |f| %>

  <div class="field">
    <%= f.collection_select :state_id, State.order(:name),  :id, :name, {:include_blank=> "Select a State"}, {:class=>'dropdown'} %>
  </div>


  ### I would like the order of the cities displayed in the drop down to be alphabetized 
  <div class="field">
    <%= f.grouped_collection_select :city_id, State.order(:name), :cities, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'} %>
  </div>        

<% end %>
4

5 回答 5

7

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

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

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

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

# 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'}
于 2013-12-24T04:39:53.050 回答
5

使用 Rails 4:

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

# app/models/state.rb
has_many :cities, -> { ordered_name }
于 2014-09-03T09:01:32.123 回答
3

如果使用 Rails 5.X,您可以使用default_scope,其中语法与@zeantsoi 答案中的略有不同。

default_scope { order('cities.name ASC') }

于 2019-07-31T11:37:32.063 回答
1

使用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'}
于 2013-12-24T04:45:20.907 回答
0

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

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

于 2016-09-08T14:26:37.350 回答