加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如果用户没有使用Devise进行身份验证,则重定向

发布时间:2020-12-16 20:22:25 所属栏目:百科 来源:网络整理
导读:我正在使用Devise与Ruby on Rails. 如果尝试访问需要身份验证的页面,将未经身份验证的用户重定向会话#新页面的推荐方法是什么? 现在我收到一条错误,表示没有路由与他们尝试访问的路由相匹配(导致生产中出现404错误). 解决方法 只需简单的添加这个方法到appl
我正在使用Devise与Ruby on Rails.

如果尝试访问需要身份验证的页面,将未经身份验证的用户重定向会话#新页面的推荐方法是什么?

现在我收到一条错误,表示没有路由与他们尝试访问的路由相匹配(导致生产中出现404错误).

解决方法

只需简单的添加这个方法到application_controller.rb
protected
  def authenticate_user!
    if user_signed_in?
      super
    else
      redirect_to login_path,:notice => 'if you want to add a notice'
      ## if you want render 404 page
      ## render :file => File.join(Rails.root,'public/404'),:formats => [:html],:status => 404,:layout => false
    end
  end

并且你可以在before_filter上调用这个方法,你想要的另一个控制器.

例如:

class HomesController < ApplicationController
  before_filter :authenticate_user!
  ## if you want spesific action for require authentication
  ## before_filter :authenticate_user!,:only => [:action1,:action2]
end

别忘了将login_path添加到routes.rb中

devise_scope :user do
  match '/sign-in' => "devise/sessions#new",:as => :login
end

注意:当我使用设备进行应用程序身份验证时,我总是使用这种方式(rails 3.2和rails 4.0.1)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读