カスケード collection_select フォームが思いどおりに機能するようになりましたが、子フィールドの更新された結果をアルファベット順に並べ替える方法を知りたいと思っています。
コントローラーでのカスタム アクション:
def update_areas
city_id = (params[:city_id].nil? || params[:city_id].empty?) ? 0 : params[:city_id].to_i
# updates artists and songs based on genre selected
if city_id == 0
@areas = []
@neighborhoods = []
else
city = City.find(params[:city_id])
# map to name and id for use in our options_for_select
@areas = city.areas.map{|a| [a.name, a.id]}
@neighborhoods = Neighborhood.where(:area_id => city.areas.each{|a| a.id}).map{|s| [s.name, s.id]}
end
@areas.insert(0, "Select an Area")
@neighborhoods.insert(0, "Select a neighborhood")
end
def update_neighborhoods
# updates songs based on artist selected
area = Area.find(params[:area_id])
@neighborhoods = area.neighborhoods.map{|s| [s.name, s.id]}.insert(0, "Select a neighborhood")
end
フォームコード:
<div id="city">
<p>City:</p>
<%= f.collection_select(:city_id, City.order('name ASC'), :id, :name, {:prompt => "Select a City"}, {:id => 'cities_select'}) %>
<br />
</div>
<div id="area">
<p>City area:</p>
<%= f.collection_select(:area_id, [], :id, :name, {:prompt => "Select an Area"}, {:id => 'areas_select'}) %>
<br />
</div>
<div id="neighborhood">
<p>Neighborhood:</p>
<%= f.collection_select(:neighborhood_id, [], :id, :name, {:prompt => "Select a Neighborhood"}, {:id => 'neighborhoods_select'}) %>
<br />
</div>
フォーム コードで Area.order('name ASC') のようなことができることはわかっていますが、都市が選択されるまで空白のままにしておきたいと思います。