当用户没有登录rails时,如何查看根视图? [英] How to have root view when user is not logged in rails?
问题描述
我正在构建一个rails应用程序,并使用Devise进行身份验证。当用户来到 www.mydomain.com
而不是 www.mydomain.com/users/sign_in $时,我想显示一个产品第一页c $ c>这是设计默认的!
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?
推荐答案
可以使用 / code> route helper在路由上添加约束,以便它们仅对登录用户可用:
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
优于@Sergio Tulentsev的答案是,这不会导致重定向或需要控制器中的任何其他逻辑。
The advantage over @Sergio Tulentsev's answer is that this does not cause a redirect or require any additional logic in the controller.
但是,您的应用程序正在重定向到 / users / sign_in
很可能是在ApplicationController中使用 before_action:authenticate_user!
,以便处理根路径的控制器需要身份验证和重定向到登录。你可以修复这个(而保留)通过跳过回调来避免安全:
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.
这篇关于当用户没有登录rails时,如何查看根视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!