ruby-on-rails 在使用devise gem之前遇到麻烦

5w9g7ksd  于 4个月前  发布在  Ruby
关注(0)|答案(2)|浏览(70)

我还在学习Rails,所以我保证我的问题很简单。
我的网站有3个控制器;我的问题是,如果一个用户没有登录,他们会自动直接发送到登录/注册页面,这是由于我在我的控制器上的before操作。我不希望当一个用户在我的根页面上时发生这种情况,该根页面与我的Pages控制器相关联?

before_action :set_script, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

字符串
我试过做实验,但我似乎不能弄清楚

before_action :set_script, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, only: [:new, :show, etc]


谢谢Stack overflow
这也是我的Rails日志

Processing by PagesController#index as HTML
Completed 401 Unauthorized in 8ms (ActiveRecord: 0.0ms | Allocations: 1163)
Started GET "/users/sign_in" for 127.0.0.1 at 2020-05-06 20:34:21 +1000
Processing by Devise::SessionsController#new as HTML
  Rendering devise/sessions/new.html.erb within layouts/application
  Rendered devise/shared/_links.html.erb (Duration: 1.6ms | Allocations: 713)
  Rendered devise/sessions/new.html.erb within layouts/application (Duration: 11.2ms | Allocations: 3029)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layouts/_nav.html.erb (Duration: 0.7ms | Allocations: 452)
  Rendered layouts/_messages.html.erb (Duration: 0.4ms | Allocations: 204)
  Rendered layouts/_footer.html.erb (Duration: 0.3ms | Allocations: 79)
Completed 200 OK in 104ms (Views: 86.1ms | ActiveRecord: 6.2ms | Allocations: 22723)

l7mqbcuq

l7mqbcuq1#

我必须从应用程序控制器中省略before_action:authenticate_user

class ApplicationController < ActionController::Base

    before_action :configure_permitted_parameters, if: :devise_controller?
    before_action :authenticate_user!
    protected

    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
    end

end

字符串

class ApplicationController < ActionController::Base

    before_action :configure_permitted_parameters, if: :devise_controller?
    protected

    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
    end

end

dz6r00yl

dz6r00yl2#

您应该保留before_action :authenticate_user!,以使默认情况下所有控制器操作都不公开
如果你需要在某个控制器中公开一个动作,那么在特定的控制器中,比如你的PagesController,你可以跳过一个before_action,比如

class PagesController < ApplicationController
      skip_before_action :authenticate_user!, only: :home

      def home
      end
    end

字符串
这将使home操作公开

相关问题