我已经让我的级联 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') 的操作,但我想在选择城市之前将其留空。