0

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

4

1 回答 1

2

您可以这样设置顺序:

@areas = city.areas.order("name asc").map{|a| [a.name, a.id]}
@neighborhoods = Neighborhood.where(:area_id => city.areas.each{|a| a.id}).order("name asc").map{|s| [s.name, s.id]}

在更新代码中:

@neighborhoods = area.neighborhoods.sort_by(&:name).map{|s| [s.name, s.id]}.insert(0, "Select a neighborhood")
于 2013-05-13T03:45:41.343 回答