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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如果用户没有使用Devise进行身份验证,则重定向到登录页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Devise与Ruby on Rails.

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

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

解决方法

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

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

例如:

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

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

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

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

猜你在找的Ruby相关文章