2016-05-01 37 views
1

我有一個rails 5應用程序,我只是試圖實現一個像按鈕功能。在我的情況下,我在做upvotes。當登錄用戶點擊按鈕時,它應該增加1.我爲用戶和管理員使用設計。Ajax請求與Rails 5應用程序獲取錯誤401(未授權)

我show.html.erb

<% if member_signed_in? %> 
<div class"movie-votes"> 
    <medium id="votes"><%= @movie.votes %> members like this film</medium> 
    <button id="upvote" type="submit">I Like this Film</button> 
</div> 

我的Ajax請求

"use strict"; 
console.log("loaded"); 
$(document).ready(function(){ 

var member = $("member"); 
var password = $("password"); 
$("#upvote").click(function() { 
console.log("clicked"); 
var id = $(this).data("id"); 

$.ajax({ 
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(member + ":" + password)); }, 
    url: "/movies/votes", 
    type: "POST", 
    data: { 
    member: "[email protected]", 
    password: "password", 
    id: id, 
votes: true 
    }, 
    success: function() { 
    var vote_counter = $("#votes"); 
    // console.log(vote_counter); 
    var current_vote = parseInt($("#votes").html()); 
    vote_counter.html(current_vote + 1); 
    alert(vote_counter); 
    } 
    }) 
}) 
}) 

MoviesController

before_action :set_movies, only: [:show, :edit, :destroy, :update, :votes] 

def votes 
@movie.update(votes: @movie.votes + 1) 
end 

private 

def set_movies 
    @movie = Movie.find(params[:id]) 
end 

的錯誤,當我打開了我越來越合作本地主機上的nsole。

loaded 
clicked 
jquery.self-660adc5….js?body=1:10246 POST http://localhost:3000/movies/votes 401 (Unauthorized) 

發生這種情況後,我點擊「我喜歡這部電影」按鈕。 Sidenote,我現在禁用了turbolinks,因爲這一直是過去的問題。 如果需要,這裏是我的GitHub

+0

你研究過類似的問題嗎? – Nithin

+0

發佈'投票'行動的整個代碼將比僅僅幾行有更多的幫助。這是添加投票功能的非常不安全的方式。你也應該檢查一下,這個用戶是否已經投了票。 – Abhinay

+0

投票動作渲染的反應是什麼? –

回答

0

很明顯,這個問題是由於認證。除了認證,你仍然有幾個問題在你的代碼,如

  • 你是不是傳遞movievotes行動id

  • 你的控制器假定params[:id]在那裏,因此試圖找到電影,但它無法得到它。

在你html代碼,在button標籤添加數據屬性:

<% if member_signed_in? %> 
<div class"movie-votes"> 
    <medium id="votes"><%= @movie.votes %> members like this film</medium> 
    <button data-movie="<%= @movie.id %>" id="upvote">I Like this Film</button> 
</div> 

在你Ajax代碼:

$(document).ready(function(){ 

    var member = $("member"); 
    var password = $("password"); // <-- this is the actual password you are passing here? 
    $("#upvote").click(function() { 
    var id = $(this).attr("data-movie"); 

    $.ajax({ 
    beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(member + ":" + password)); }, 
     url: "/movies/votes", 
     type: "POST", 
     data: { 
     member: "[email protected]", 
     password: "password", 
     id: id, 
     votes: true 
     }, 
     success: function() { 
     var vote_counter = $("#votes"); 
     // console.log(vote_counter); 
     var current_vote = parseInt($("#votes").html()); 
     vote_counter.html(current_vote + 1); 
     alert(vote_counter); 
     } 
    }); 
    }); 
}); 

PS:我不知道,如果它是一個正確的建立投票功能的方式。我建議使用像act_as_votable這樣的寶石,它會更整潔。

相關問題