scripter scripter - 7 months ago 25
Ruby Question

How to give controller name as url in ajax request in ruby on rails?

I am getting Routing Error No route matches [POST] "/update_cities" Below is my code. I am not able to find out what exact value should be given in ajax request in url. please help me out, I am new to rails.

**Ajax request**
$(document).ready(function(){
$('#state_select').on('change', function(){
$.ajax({
url: "/update_cities",
type: "POST",
data: {state_id: $(this).val()}
})
.done(function(data) {
$.each(data, function (i, item) {
$('#city_select').append($('<option>', {
value: item.value,
text : item.text
}));
});
});
}); });

**Route**
post 'colleges/update_cities' => 'colleges#update_cities'

**Action in colleges_controller file**
def update_cities
@cities = City.where("state_id = ?", params[:state_id])
respond_to do |format|
format.js
end
end

Answer

Routing Error No route matches [POST] "/update_cities"

According to your route, the should be changed to colleges/update_cities. The below code should work

$(document).ready(function(){
$('#state_select').on('change', function(){
$.ajax({  
  url: "/colleges/update_cities",
  type: "POST",
  data: {state_id: $(this).val()}
})
.done(function(data) {
   $.each(data, function (i, item) {
    $('#city_select').append($('<option>', { 
        value: item.value,
        text : item.text 
    }));
   });
  });
  }); });