2017-12-02 177 views
0

我正在构建一个reddit/angellist克隆。我希望能够upvote和downvote没有页面重新加载。我通过votescontroller已经阿贾克斯设置:如何实现coffeescript在401 ajaxerror之后工作?

respond_to do |format| 
    format.html { redirect_to request.referer } 
    format.js 
end 

然后在upvote.js.erb:

$(document).ready(function(e) { 
    $("#vote-sum").html("<%= pluralize(@votable.votes.sum(:value), 'vote') %>"); 
}); 

到目前为止都很好。点击时立即变化。

这一切都发生在用户登录时。当用户没有登录,并按下上行链接时,我得到401,因为我使用Devise我在我的票控制器中有before_action :authenticate_user!。我得到这个作为我的本地服务器上的输出:

Started POST "/items/11/upvote" for 127.0.0.1 at 2017-12-02 17:52:06 +0100 
Processing by VotesController#upvote as JS 
    Parameters: {"item_id"=>"11"} 
    Item Load (1.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 ORDER BY "items"."created_at" DESC LIMIT $2 [["id", 11], ["LIMIT", 1]] 
Completed 401 Unauthorized in 24ms (ActiveRecord: 1.2ms) 

我想自动发送用户登录页面。所以,我用Google搜索的答案,发现一个,具有极大的答案:

https://stackoverflow.com/a/10460074/6430382

我要插入几行代码:

$ -> 
    $("a").bind "ajax:error", (event, jqXHR, ajaxSettings, thrownError) -> 
    if jqXHR.status == 401 # thrownError is 'Unauthorized' 
     window.location.replace('/users/sign_in') // or with .replace(this) 

然而,当我将这些行添加这是行不通的。我将$("a")更改为$(document)。甚至改变了这种香草JS:

$(function() { 
    return $(document).bind("ajax:error", function(event, jqXHR, ajaxSettings, thrownError) { 
    if (jqXHR.status === 401) { 
     return window.location.replace('/users/sign_in'); 
    } 
    }); 
}); 

旁注:一个正常的console.log( '!')和警报( '!')工作在application.jsvotes.coffee代码罚款。

我希望代码将用户重定向到页面中的设计符号。

其他类似的资源,我已经看了:

https://stackoverflow.com/a/34434921/6430382

https://stackoverflow.com/a/9903564/6430382

Devise authenticate_user! breaks when making remote: true requests to a non-devise controller action

回答

0

随着我回来了,一个小破开始研究,我没其他一些问题”以前见过。

解这里:https://stackoverflow.com/a/45168313/6430382

创建方法上述(前)&实施before_action :authenticate_user!

def check_user 
    return if user_signed_in? 
    redirect_to new_user_session_path, error: 'You must log on to view this part of the site' 
end 

添加到控制器

class VotesController < ApplicationController 
    before_action :check_user 

    ... 
end