I am currently looking for a software/web development job preferably as a Rails-based developer.
Please email me at weston@westonganger.com. Thanks in advance for any leads!

Redirect To Specific Page If User Is Not Logged In

Posted by Weston Ganger

In Devise, when you want to authenticate a user before they can access anything in your controller or application you must add this line to your controller:

before_filter :authenticate_user!

This will redirect the user to the default login page if they are not logged in

But what if you want to redirect them to a different page? By overwriting the method in your application controller:

### app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  def authenticate_user!
    if user_signed_in?
      redirect_to your_path, notice: "Please Login to view that page!"

If you are using authenticate_user! in your application controller then you are probably only showing the root page without authenticating the user, in which case you need to add an if to the end of the redirect_to statement, otherwise you will get an infinite redirect loop

redirect_to your_path, notice: "Please Login to view that page!" if request.original_fullpath != your_path

Related External Links:

Article Topic:Software Development - Rails

Date:October 09, 2015

Recommended Posts