首次进入站点的根时设计身份validation错误

当用户输入我们网站的根目录或注销时,Devise身份validation显示“您需要首次登录或注册才能继续”。 页面重新加载后,此消息消失。

我们网站的根目录设置为控制器,它具有:

before_filter :authenticate_user! 

我们需要这个控制器作为根。 如何消除此消息?

正确的解决方案是设置一个经过validation的块,如官方维基中所述: https : //github.com/plataformatec/devise/wiki/How-To : -Require- authentication-for-all- pages

  authenticated :user do root to: 'home#index', as: :authenticated_root end root to: redirect('/users/sign_in') 

只有在登录后才会调用范围经过authenticated块,因此您可以愉快地将用户定向到您选择的控制器。 在示例中,它在未经身份validation时将其重定向到登录页面,但这可能是您的路线中的任何操作。

你想删除索引上的消息吗? 如果是这样,你可以这样做:

 before_filter :authenticate_user!, :except => [:index] 

您也可以向arrays添加其他操作。

请注意,这不会调用authenticate_user! 在指定的操作上,因此请确保不需要为给定的操作validation用户!

我没有找到比定义更好的解决方案

 unauthenticated: '' 

在/config/locales/devise.en.yml文件中。

假设您已经封装了您的设计错误消息,如下所示。

 

<%= notice %>

<%= alert %>

您可以将以下CSS代码添加到根控制器的索引视图文件中。

  

这应该隐藏来自您网站的根目录的错误消息。

在所有页面(登录,注册等除外)都受到before_action :authenticate_user!保护的情况before_action :authenticate_user! ,我会覆盖Devise的SessionController如下所示:

app/controllers/sessions_controller.rb

 class SessionsController < Devise::SessionsController def new if flash[:alert] == unauthenticated_message flash.delete(:alert) unless requested_protected_page? end super end private def requested_protected_page? session[:user_return_to] != root_path end def unauthenticated_message I18n.t('devise.failure.unauthenticated') end end 

然后告诉你的config/routes.rb文件使用那个被覆盖的控制器:

 devise_for :users, controllers: { sessions: :sessions, } 

您可以在控制器中创建单独的操作,只是为了解决用户是否登录,然后重定向到所需的位置。

 class WelcomeController < ApplicationController skip_before_filter :authenticate_user!, only: :root def index end def root flash.keep redirect_to current_user ? welcome_index_path : new_user_session_path end end 

这应该工作,当然你应该在ApplicationController中

 before_filer: authenticate_user! 

并在路由根目录中配置为欢迎#root