Search code examples
ruby-on-railsdeviseruby-on-rails-6

Routing error when opening authenticated root when not signed in


I'm running into a strange issue with my Rails 6 app. I'm using devise for two different models and have each scoped appropriately (I believe). I have an authenticated_root path set up in my devise scope:

  devise_scope :tenant do
    authenticated :tenant do
      namespace :tenants do
        get 'home/my_key', as: :authenticated_root
        get 'home/guest_pass_list'
      end
    end
  end

In the controller:

class Tenants::HomeController < ApplicationController
  before_action :authenticate_tenant!, only: %i[my_key, guest_pass_list]

This works perfectly fine when the tenant follows the typical sign in path, but when a user tries do open /tenants/home/my_key directly when not signed in, a routing error is thrown. It seems like it should instead, redirect to the tenants/sign_in path.

What am I missing here? This has to be a configuration issue on my end.


Solution

  • You'll need to define the namespace :tenants outside the authenticated :tenant block, because the authenticated macro defines the routes only for "authenticated" accounts. So, for an "unauthenticated" account, the route doesn't exist and it throws a routing exception.

    More info: https://github.com/heartcombo/devise/wiki/How-To:-Define-resource-actions-that-require-authentication-using-routes.rb

    The redirect will be handled by the before_action :authenticate_tenant! callback in your controller. By the way, you should also change %i[my_key, guest_pass_list] to %i[my_key guest_pass_list] (note the , removal):

    >> %i[my_key, guest_pass_list]
    => [:"my_key,", :guest_pass_list]
    >> %i[my_key guest_pass_list]
    => [:my_key, :guest_pass_list]