title: Populate dropdown list upon selecting a value from another dropdown list
body: <p>I'm trying to populate one drop down list based on the selection of another drop down list in my rails project. The only difference is that both drop down lists should be populated from one model.</p>
  
  <p>The model is <strong>City</strong>, and it has <strong>name</strong> and <strong>state</strong>. </p>
  
  <p><strong>name</strong> is the city name, and <strong>state</strong> is the state to which the city belongs.
  For example, a city object would be :</p>
  
  <pre><code>id = 1
  name = LOSANGELES
  state = CA
  </code></pre>
  
  <p>I've checked <a href="https://stackoverflow.com/questions/37230426/rails-4-how-to-update-a-collection-select-based-on-another-collection-select-th">Rails 4: How to update a collection_select based on another collection_select through AJAX?</a>
   and other links but I can't seem to figure out how to populate the city drop down list from the same Model as the first dropdown</p>
  
  <p>Here's my code :</p>
  
  <p>controllers/city_stats_controller.rb :</p>
  
  <pre><code>def city_stats
  @state = params[:state]
  @cities = City.select(:name).all.where(:state =&gt; state)
  
   respond_to do |format|
     format.json  { render :json =&gt; @cities }      
   end
  end
  </code></pre>
  
  <p>views/city_stats/city_stats.html.erb :</p>
  
  <pre><code>&lt;div class="row"&gt;
      &lt;label&gt;State &lt;span&gt;*&lt;/span&gt;&lt;/label&gt;
      &lt;%= collection_select :city, :state, City.select(:state).uniq.order('state ASC'), :id, :state, {:prompt =&gt; 'Select a State'}, {id: 'state', multiple: false} %&gt;
  
      &lt;label&gt;City &lt;span&gt;*&lt;/span&gt;&lt;/label&gt;
      &lt;%= collection_select :city, :name, [], :id, :name, {:prompt =&gt; 'Select a City'}, {id: 'name', multiple: false} %&gt;
  &lt;/div&gt;
  
  &lt;script type="text/javascript"&gt;
  $(document).ready(function() {
  $("#state").on('change', function(){
    $.ajax({
      url: "/admin/city_stats",
      type: "GET",
      data: {state: $(this).val()},
      success: function(data) {
        $("#city").children().remove();
        // Create options and append to the list
        var listitems = []; 
        $.each(data,function(key, value) { 
          listitems += '&lt;option value="' + key+ '"&gt;' + value + '&lt;/option&gt;';    }); 
      $("#city").append(listitems);
      console.log(listitems);
       }
      })
    });
  });
  &lt;/script&gt;
  </code></pre>
  
  <p>Any help is much appreciated!</p>