Search code examples
ruby-on-railsdevise

How to have root view when user is not logged in rails?


I am building a rails app and I use Devise for authentication. I want to show a product first page when user comes to www.mydomain.com instead of www.mydomain.com/users/sign_in which is devise default!

I will also want to show a different root view when user is logged in. This feels like a very common use case, is there a easy way to do this? Is this there in documentation or can anyone help me with this?


Solution

  • You can use the authenticated route helper provided by Devise to add a constraint on the routes so that they are only available to logged in users:

    Rails.application.routes.draw do
      devise_for :users
    
      authenticated :user do
        root 'secret#index', as: :authenticated_root
      end
    
      root "home#index"
    end
    

    The advantage over @Sergio Tulentsev's answer is that this does not cause a redirect or require any additional logic in the controller.

    However the reason your app is redirecting to /users/sign_in is most likely that you are using before_action :authenticate_user! in your ApplicationController so that the controller handling the root path is requiring authentication and redirecting to the sign in. You can fix this (while retaining a secure by default setup) by skipping the callback:

    class HomeController < ApplicationController
      skip_before_action :authenticate_user!
      # ...
    end
    

    This applies to any controller that should not require authentication. You can skip specific actions by using the only and except options. Just remember that whitelists are more secure than blacklists.