3

我終於想出瞭如何使用this tutorial實現動態選擇菜單。分組收藏選擇字母順序軌道

一切正常,但一個人如何組織城市按名稱下拉....

下面是所有我寫的代碼。 (請讓我知道如果你需要任何進一步的信息)

新建軌道請幫助:)

VIEWS

<%= 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 %> 

回答

6

選項1:在你的City模型中,添加一個default scope指示城市按字母順序返回:

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

City對象的集合將默認按名稱按字母順序返回。

選項2:定義一個named scopeState模型返回按字母順序排列的城市爲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'} 
+0

真棒,感謝的人:d –

+0

我可以問你實現哪些解決方案? – zeantsoi

+0

我嘗試了兩個,他們都工作。但我實施了第一個。再次感謝 –

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'} 
5

使用Rails 4:

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

# app/models/state.rb 
has_many :cities, -> { ordered_name } 
0

與其他人一樣在這個線程,我有問題得到這個與範圍一起工作。相反,我加入另一個關聯到State模式得到了在導軌5這個工作:

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