Reputation: 19220
I’m using Rails 4.2.5. If a user is logged in, I want to redirect them if they visit http://localhost:3000/ to http://localhost:3000/user_objects . So I have added this to my config/routes.rb file
constraints(AuthenticatedUser) do
root :to => "user_objects"
end
root 'pages#index'
Then I have this file in lib/authenticated_user.rb …
class AuthenticatedUser
def self.matches?(request)
user_signed_in?
end
end
Unfortunately, when I’m logged in, and I access http://localhost:3000/, I get this error
NameError
uninitialized constant AuthenticatedUser
Any idea how I can redirect the user to the suggested page if someone is logged in?
Edit: My config/routes.rb file is as follows ...
resources :user_objects, except: :update do
member do
patch :create
put :create
end
get :find_by_user_object_and_day, on: :collection
get :find_totals, on: :collection
end
get "users/edit" => "users#edit"
resources :users
root 'pages#index'
get '/auth/:provider/callback', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
delete '/logout', to: 'sessions#destroy'
Upvotes: 0
Views: 57
Reputation: 15954
The documentation on constraints
recommends putting custom constraint classes to lib/constraints
.
Anyway, for the class to be recognized in routes
you should have it autoloaded. Add the directory where the constraint resides to the list of autoloaded directories in application.rb
:
# config/application.rb
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W[...
#{config.root}/lib/constraints]
Upvotes: 0
Reputation: 4443
In the controller action for whatever root is, you can just say:
if current_user
redirect_to user_objects_path #look up the rails helper
end
Upvotes: 2