rails 4- 401未经授权的错误处理 [英] rails 4- 401 Unauthorized error handling

查看:111
本文介绍了rails 4- 401未经授权的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的定额类问题网站,其中登录使用的是devise.我试图使用ajax在问题索引本身中呈现表单.除了没有用户登录时,一切似乎一切正常,服务器显示401未经授权已完成,并且似乎什么也没有发生. 控制台响应:

I am making a simple quora like question answer site where login is using devise. I was trying to render form in the question index itself using ajax. Everything seems to work fine except that when no user is logged in The server says 401 unauthorised Completed and nothing seems to happen. Console Response:

Started GET "/questions/new" for 127.0.0.1 at 2017-07-18 18:30:54 +0530 Processing by QuestionsController#new as JS Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)

Started GET "/questions/new" for 127.0.0.1 at 2017-07-18 18:30:54 +0530 Processing by QuestionsController#new as JS Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)

控制器: def new @question = Question.new(:user=>current_user) respond_to do |format| format.js {} end end

controller: def new @question = Question.new(:user=>current_user) respond_to do |format| format.js {} end end

由于问题控制器中的before_action :authenticate_user!,我知道这一点. 网络响应中的Chrome控制台也显示您需要登录或注册才能继续."

I know this because of the before_action :authenticate_user! in the questions controller. Chrome console in Network response also says "You need to sign in or Sign Up before continuing."

此外,我尝试了byebug,但后来知道流程从未达到新的动作.

Also, i tried byebug but came to know that the flow never reaches the new action.

我想知道如何处理此错误.要显示我需要登录或注册为页面顶部的通知或警报,或重定向到登录页面.

I want to know how to handle this error. To either show that I need to sign in or signup as a notice or alert at top of the page or redirect to the sign in page.

我正在使用remote: true来调用ajax.在索引页面上的新问题"链接中.

I am using remote: true for calling ajax. in New Question link on the index page.

推荐答案

这在控制器中最容易处理.创建一个名为"check_user"的方法:

This is easiest to deal with in the controller. Create a method called "check_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

然后,我们可以决定要为每个控制器的用户检查哪些页面.如果您想限制用户的每个问题页面,只需执行以下操作:

Then we can decide what pages we want to check for the user for each controller. If you want to limit every question page for users, then simply do:

class QuestionsController < ApplicationController
  before_action :check_user

  ...
end

这将在每个Questions Controller操作之前执行该方法.或者,如果您希望任何人都可以查看并说出索引并显示页面,而其他人则不显示:

This will perform the method before every Questions Controller action. Alternatively, if you want anyone to be able to view say the index and show pages but not any others:

before_action :check_user, except: [:index, :show]

这篇关于rails 4- 401未经授权的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆