Surge Pedroza Surge Pedroza - 1 month ago 14
Ruby Question

Grouped Collection Select Alphabetical Order Rails

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 :)


<%= 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'} %>

### 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'} %>

<% end %>


Option 1: In your City model, add a default scope that directs cities to be returned in alphabetical order:

# app/models/city.rb
default_scope :order => ' ASC'

Collections of City objects will, by default, be returned in alphabetically by name.

Option 2: Define a named scope in your State model that returns cities in alphabetical order as an association on a State object:

# app/models/state.rb
scope :cities_by_name, -> { cities.order(name: :asc) } # Rails 4

scope :cities_by_name, cities.order("name ASC") # Rails 3

Then, pass your scoped query to your grouped_collection helper:

f.grouped_collection_select :city_id, State.order(:name), :cities_by_name, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'}