我正在构建一个rails应用程序,我使用Devise进行身份验证。我希望在用户访问www.mydomain.com
时显示产品首页,而不是默认设置为www.mydomain.com/users/sign_in
!
我还希望在用户登录时显示不同的根视图。这感觉就像一个非常常见的用例,是否有一种简单的方法可以做到这一点?这是在文档中还是有人可以帮助我吗?
答案 0 :(得分:4)
您可以使用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
的原因很可能是您在ApplicationController中使用before_action :authenticate_user!
,以便处理根路径的控制器需要身份验证并重定向到登录。可以通过跳过回调来修复此问题(同时保留默认安全设置):
class HomeController < ApplicationController
skip_before_action :authenticate_user!
# ...
end
这适用于任何不需要身份验证的控制器。您可以使用only
和except
选项跳过特定操作。请记住,白名单比黑名单更安全。
答案 1 :(得分:2)
我这样做,根路径有一条路线:
# 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