Rails - how to sort the results of a cascading collection select form -


i've gotten cascading collection_select form working want, want figure out how can sort updated results of children fields alphabetically.

my custom actions in controller:

def update_areas    city_id =  (params[:city_id].nil? || params[:city_id].empty?) ? 0 : params[:city_id].to_i    # updates artists , songs based on genre selected    if city_id == 0      @areas = []      @neighborhoods = []      else       city = city.find(params[:city_id])       # map name , id 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 area")   @neighborhoods.insert(0, "select 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 neighborhood") end 

form code:

<div id="city">     <p>city:</p>     <%= f.collection_select(:city_id,  city.order('name asc'),  :id, :name, {:prompt   => "select city"}, {:id => 'cities_select'}) %>     <br /> </div>  <div id="area">     <p>city area:</p>     <%= f.collection_select(:area_id, [], :id, :name, {:prompt   => "select area"}, {:id => 'areas_select'}) %>     <br /> </div>  <div id="neighborhood">     <p>neighborhood:</p>     <%= f.collection_select(:neighborhood_id, [], :id, :name, {:prompt   => "select neighborhood"}, {:id => 'neighborhoods_select'}) %>     <br /> </div> 

i know can area.order('name asc') in form code, want leave blank until city has been selected.

you can set order doing this:

@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]} 

and in update code:

@neighborhoods = area.neighborhoods.sort_by(&:name).map{|s| [s.name, s.id]}.insert(0, "select neighborhood") 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -