如果用户未使用Devise进行身份validation,则重定向到登录页面
我正在使用Devise和Ruby on Rails。
如果未经身份validation的用户尝试访问需要身份validation的页面,建议将其重定向到会话#new页面?
现在我得到一个错误,指出没有路由匹配他们尝试访问的路由(导致生产中出现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
注意:我总是使用这种方式为我的应用程序validation设计..(rails 3.2和rails 4.0.1)
你可以像GeekTol那样写,或者只是放
before_action :authenticate_user!
在你的控制器中。
在这种情况下,devise使用默认的authenticate_user! 方法,将重定向到“user_session_path”并使用默认的Flash消息。
没有必要重写authenticate_user! 方法,除非你想自定义它。
我以为你可以添加:before_action:authenticate_user! 到需要用户登录的每个控制器。
我是Rails的初学者,但我在自己的搜索中找到了它,它在我的应用程序中运行良好。
您应该参考Devise自己的如何: 如何:当用户无法进行身份validation时重定向到特定页面 。
我能想到的另一个选择是创建包裹受保护路由的路由约束。 你最好坚持Devise的方式,但这是一个例子:
#On your routes.rb constraints(Constraints::LoginRequired) do get '/example' end #Somewhere like lib/constraints/login_required.rb module Constraints class LoginRequired def self.matches?(request) #some devise code that checks if the user is logged in end end end
在config / routes.rb中添加此代码devise_for :users
和resources :users
,您可以在视图中生成设计。