用户未登录rails时如何获得root视图?
我正在构建一个rails应用程序,我使用Devise进行身份validation。 当用户访问www.mydomain.com
而不是www.mydomain.com/users/sign_in
,我想展示产品第一页,这是设计默认值!
我还想在用户登录时显示不同的根视图。这感觉就像一个非常常见的用例,是否有一种简单的方法可以做到这一点? 这是文档中还是有人可以帮助我吗?
您可以使用authenticate
路由帮助程序在路由上添加约束,以便它们仅对登录用户可用:
Rails.application.routes.draw do devise_for :users authenticated :user do root 'secret#index', as: :authenticated_root end root "home#index" end
优于@Sergio Tulentsev的答案是,这不会导致重定向或需要控制器中的任何其他逻辑。
但是,您的应用重定向到/users/sign_in
的原因很可能是您正在使用before_action :authenticate_user!
在您的ApplicationController中,以便处理根路径的控制器需要身份validation并重定向到登录。您可以通过跳过回调来修复此问题(同时保留默认安全设置):
class HomeController < ApplicationController skip_before_action :authenticate_user! # ... end
这适用于任何不需要身份validation的控制器。 您可以使用only
和except
选项跳过特定操作。 请记住,白名单比黑名单更安全。
我这样做,根路径有一条路线:
# routes.rb root to: 'home#index'
然后检查当前用户并确定要显示的页面。
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