【问题标题】:Encountering endless loop with error: Filter chain halted as :require_no_authentication rendered or redirected遇到无限循环并出现错误:过滤器链因 :require_no_authentication 呈现或重定向而停止
【发布时间】:2016-05-10 02:31:54
【问题描述】:

我有两个模型供应商和客户,在应用程序控制器中我为每个模型定义了after_sign_in_path_for 方法,但是在为客户注册并确认后,当我登录时,我重定向到供应商登录页面而不是@987654322 @。出现这个问题是因为我将两个模型的方法都放在了应用程序控制器中,我是否应该将每个方法都放在相应的会话控制器中?

我认为错误重定向的原因是无限循环。下面的应用程序控制器代码有什么问题吗? 我只写了这个应用程序控制器,其他的都是内置的。

 class ApplicationController < ActionController::Base
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception
    before_action :authenticate!

    def after_sign_in_path_for(user)
        if user && user.is_a?(Customer)
            customer_dashboard_path
        elsif user && user.is_a?(Vendor)
            vendor_dashboard_path
        end
    end

    def after_sign_out_path_for(user)
        if user && user.is_a?(Customer)
            root_path
        elsif user && user.is_a?(Vendor)
            root_path
        end
    end

    def after_inactive_sign_up_path_for(user)
        if user && user.is_a?(Customer)
            root_path
        elsif user && user.is_a?(Vendor)
            root_path
        end
    end

  def authenticate!
      if @current_user == current_customer
          :authenticate_customer!
          elsif @current_user == current_vendor
          :authenticate_vendor!
      end
  end

end

【问题讨论】:

    标签: ruby-on-rails ruby redirect model-view-controller devise


    【解决方案1】:

    您使用不同的参数编写了两次相同的方法(方法覆盖)。所以它总是会选择第二种方法after_sign_in_path_for(vendor)。例如,您可以将方法名称更改为您期望的名称并相应地调用方法。

     def after_sign_in_path_for_customer(customer)
       dashboard_path
     end
    
     def after_sign_in_path_for_vendor(vendor)
       dashboard_path
     end
    

    或者你可以有一个像下面这样的通用方法

    def after_sign_in_path_for(user)
      if user && user.is_a?(Vendor)
         redirect to vendor dashbord
      elsif user && user.is_a?(Customer)
         redirect to customer dash board
      end
    end 
    

    【讨论】:

    • 我尝试了第二个例子,但它并没有改变网站的行为,我忘了说我使用的是devise,这些方法是devise提供的
    • 模型之间的关系是什么?客户和供应商?他们是吗?我想因为您之前对两个 authenticate_vendor 都进行了操作!并验证_客户! .其中一个返回 false 并重定向到登录页面,因为它认为您未登录。
    • 两个模型之间没有关系,都服务于两个不同的目的
    • 好的,所以你有两个前置过滤器 authenticate_customer!和authenticate_vendor! .当以客户身份登录时,这两个返回 true 还是为 authenticate_vendor 返回 false!因此重定向
    • 是的,这可能是问题的原因,我可以用 iff 语句定义一个新方法来检查要验证哪种类型的用户吗?
    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 2017-02-11
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多