Getting This page isn’t working redirected you too many times error when trying to redirect to login page

Viewed 77

I have a simple application controller, and I puzzled by its behavior. It just won't let me connect to a login page

class ApplicationController < ActionController::Base
  before_action :do_atthestart

  protected
    def do_atthestart
       redirect_to login_path
    end
end

Once the "redirect_to login_path" is hit, I get the error on a browser that says

This page isn’t working redirected you too many times

And on the log I get the following information

Started GET "/login" for .................................. Processing by SessionsController#new as HTML Redirected to http://127.0.0.1:3000/login Filter chain halted as :do_atthestart rendered or redirected Completed 302 Found in 3ms (ActiveRecord: 0.0ms | Allocations: 282)

Does anyone have any idea how to move forward beyond it?

Thank you in advance

1 Answers

The before_action is creating an endless loop.

It applies to any action in any controller that inherits from ApplicationController, including SessionsController#new. The callback redirects to that action, which then calls the callback, which redirects to that action, and so on.

One technique would be to load the before_action in each controller. Then, in your sessions controller, you could except the function from the callback:

class SessionsController < ApplicationController
  before_action :do_atthestart, except: :new
end
Related