2016-10-19 3 views
0

Ajax 요청은 여전히 ​​나에게 새롭지 만 내가 좋아하는 요리법을 허용하는 버튼이있는 래서 피 색인이있다.Rails 4 + jQuery : PUT ajax request

$(".favorite").click(function(){ 
     $(this).toggleClass("favorited"); 
     var recipe_id = $(this).data("recipe"); 

     // displays properly when I console.log() it 
     var url_path = '/recipes/' + recipe_id + '/favorite' 


     $.ajax({ 
      url: url_path, 
      type: 'PUT' 
     }) 
    }) 

하지만 내 개발자 콘솔에서 다음의 jQuery 기능을 사용하여 ...

favorite_recipe PUT /recipes/:id/favorite(.:format) recipes#favorite 

:

<i class="favorite" data-recipe="<%= recipe.id %>"> 

... 난 경로에 PUT 요청을 사용하는 것을 시도하고있다 , 404 오류가 발생하고 표시된 URL이 http://localhost:3000/recipes/:recipe_id/favorite이 아닌 Request URL:http://localhost:3000/recipes입니다.

내가 뭘 잘못하고 있니? ID를 제공하려면 데이터 매개 변수를 사용해야합니까?

+0

gil.neo가 말한 것처럼이 즐겨 찾기 경로가있는 routes.rb가 있는지 확인하십시오. 또한, 당신은 귀하의 요리법 컨트롤러에 다음과 같은 방법이 필요하다고 생각합니다 : gil.neo가 route.rb 경로를 가지고 있는지 확인하십시오. '데프 좋아하는 @recipe = Recipe.find (PARAMS [: ID]를) 또한, 나는 당신이 같은 당신의 조리법 컨트롤러의 방법이 필요 믿습니다! Recipe.increment @ (: 좋아하는) 끝' – tfantina

답변

1

좋아, 나는 그 요청에 대한 경로가 있음을 알았 기 때문에 내 대답이 바뀌고 있습니다.

컨트롤러에서 요청을 제대로 처리하지 않아이 오류가 발생했다고 생각합니다. 컨트롤러에 JSON 요청을 처리하도록 다음을 추가하십시오.

respond_to do |format| 
     format.json do 
     render :json => {success: 'yes'} 
     end 
end 
0

한번 시도하십시오.

$(".favorite").click(function(){ 
    $(this).toggleClass("favorited"); 
    var recipe_id = $(this).data("recipe"); 

    // displays properly when I console.log() it 
    var url_path = "<%= favorite_recipe_path %>" 


    $.ajax({ 
     url: url_path, 
     type: 'PUT', 
     data : JSON.stringify({id: recipe_id}), 
     dataType: "json", 
    }) 
}) 
+0

@ 제레미 토마스, 이것을 시도/ – Sravan

+0

@ 제레미 Thoas, 이것을 구현 했습니까? – Sravan

+0

ajax가 type 대신 method를 사용해야합니까? –