2016-05-02 11 views
2

私は特定の州を選択して都市を表示しようとしています。しかし、私はどのように "collection_selectで選択されたオプション"のデータを使ってajaxリクエストを行うか分かりません。collection_selectでレールにajax検索を行うにはどうすればよいですか?

form 

%= form_for @college do |f| %> 
<div class="form-group"> 

    <%= f.label "Select state"%> 
    <%= f.collection_select(:state_id, @state, :id, :state, {}, {class: "form-control", :id => "state_select"})%> 
</div><br> 
    <div class="form-group"> 
    <%= f.label :city_id, "Select city"%> 
    <%= f.collection_select(:city_id, @city, :id, :city, {}, {class: "form-control", :id => "city_select"})%> 
</div><br> 
<div class="form-group"> 
    <%= f.label :college, "college Name"%> 
    <%= f.text_field :college, class: "form-control", placeholder: "Enter college name", required: true%> 
    <br> 
</div> 
<div class="form-group"> 
    <%= f.submit class: "btn btn-primary"%> 

</div> 
<% end %> 

Controller for update 
def update_cities 
@cities = City.where("state_id = ?", params[:state_id]) 
respond_to do |format| 
    format.js 
end 
end 

JS incomplete 

$('#state_select').on('change', function(){ 
$('#city_select').value.empty; 
}) 

答えて

0

あなたはajax呼び出しを行い、javascriptを介してデータを取り込む必要があります。

$('#state_select').on('change', function(){ 
    $.ajax({ 
     url: "/update_cities", 
    }) 
    .done(function(data) { 
     $.each(data, function (i, item) { 
     $('#city_select').append($('<option>', { 
      value: item.value, 
      text : item.text 
     })); 
     }); 
    }); 
}); 
+0

ノールート一致するエラーを取得していますが、私は私のroute.rbに言及している**ポスト「大学の/のupdate_cities」=>「大学の#のupdate_cities」**また、あなたは私たちがPaaSのに必要とは思いません状態IDも要求に含まれます。 – scripter

関連する問題