问题
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?
回答1:
You can use the authenticate
route helper 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.
回答2:
I'd do this way, have a single route for root path:
# routes.rb
root to: 'home#index'
Then check for current user and decide which page to show.
class HomeController < ApplicationController
def index
if current_user
redirect_to some_page_path
# or render some content directly in this response
render :some_view
else # no logged-in user
# same, render or redirect
end
end
end
来源:https://stackoverflow.com/questions/43429845/how-to-have-root-view-when-user-is-not-logged-in-rails