【问题标题】:Using Devise before_action :authenticate_user! doesn't do anything使用设计 before_action :authenticate_user!什么都不做
【发布时间】:2019-10-15 21:07:31
【问题描述】:

我试图要求登录我的 Rails 4 网站上的所有页面。 在 ApplicationController 中我添加了before_action :authenticate_user!,但它根本没有做任何事情。我尝试将相同的before_action :authenticate_user! 添加到另一个控制器,它工作正常。

我是否需要对 ApplicationController 执行其他操作,以使所有操作都需要登录(注册/登录除外)?

【问题讨论】:

  • 这应该没问题,只要你的其他控制器确实继承自 ApplicationController...

标签: ruby-on-rails devise


【解决方案1】:

这是我们使用的实际代码:

#app/controllers/application_controller.rb
Class ApplicationController < ActionController::Base
   #Actions
   before_action :authenticate_user! #-> routes to the login / signup if not authenticated
end

你可能有两个问题:

--

确保您的其他控制器继承自 application_controller

#app/controllers/other_controller.rb
Class OtherController < ApplicationController 
    ...
end

--

您以某种方式“跳过”before_action 回调

如果您在任何地方使用skip_before_action,则需要将其删除。这可能会导致您的authenticate_user! 方法出现问题。为了解决这个问题,我首先会在没有任何skip_before_action 回调的情况下进行测试,然后看看是什么让它正常工作


进一步说明 - signin / signup 无关紧要。它们都继承自Devise 控制器;他们会根据需要运行。

【讨论】:

  • 我刚刚发现我使用的是 ActionController::Base 而不是仅仅从 ApplicationController 继承。我回去写一个答案,但你在我面前:)
  • 非常感谢您的支持和接受!现在可以用了吗?
【解决方案2】:

2019 年更新

在您的 routes.rb 文件中,您可能只提到了 authenticated_user 路径,如下所示

authenticated :user do
    root to: 'home#index', as: :root_app
  end

您也应该提及 unauthenticated_user 路径以使其正常工作,或者仅提及 root 路径而没有 unauthenticated_userauthenticated_user

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    相关资源
    最近更新 更多