我在Ruby on Rails中使用Devise。
如果未经身份验证的用户尝试访问需要身份验证的页面,建议将未身份验证的用户重定向到session#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
注意:在使用devise进行我的应用程序身份验证时,我总是使用这种方式。(rails 3.2和rails 4.0.1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句