Grouped Collection Select Alphabetical Order Rails

Viewed 4548

I finally figured out how to implement Dynamic Select menus using this tutorial.

Everything works, But how does one organize the Cities in the Dropdown by Name....

Below is all of the code I've written. (Please let me know if you need any further information)

New to rails please help :)

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 %>
5 Answers

If using Rails 5.X, you can use default_scope, in which the syntax is slightly different than in @zeantsoi answer.

default_scope { order('cities.name ASC') }

Related