不使用 Devise 为登录用户指定不同的根路径 [英] Specify a different root path for logged in users without using Devise

查看:54
本文介绍了不使用 Devise 为登录用户指定不同的根路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户已登录,我希望 users#show 为路由路径.否则,路由路径应该是 static_pages#home.

If the user is logged in, I want users#show to be the route path. Else, the route path should be static_pages#home.

请告诉我如何在不使用 Devise gem 的情况下实现这一目标.

Please let me know how I can achieve this without using the Devise gem.

推荐答案

我认为在路由文件中使用 if/else 语句是不正确的.将其视为路由文件中的业务逻辑.您的业​​务逻辑应该在您的模型中(不一定是 ActiveRecord,任何普通的旧 ruby​​ 类都可以)或者它是否更适合您的控制器(如本例).

I think having if/else statements in your routes file isn't right. Think of it as a business logic in your routes files. Your business logic should be in your Models (not necessarily an ActiveRecord, any plain old ruby class would do) or if it better fits in your controller (like in this case).

假设您没有使用诸如warden之类的任何中间件来进行用户身份验证,则必须在路由文件中进行数据库查询和身份验证.这应该是它不属于那里的另一个标志.打个比方,这就像在视图中执行 SQL 查询一样.

Suppose you are not using any middleware like warden to do user authentication, you would have to do database queries and authentication right in your routes file. This should be another flag that it does not belong there. As an analogy, it is like doing SQL queries in your views.

好吧,我希望我能证明这一点.现在,让我们回到一个可能的解决方案.

Alright, I hope I justified the point. Now, let's get back to a possible solution.

为某些控制器操作设置根路径,您将在其中执行 if/else 检查并重定向到正确路径.

Set a root path to some controller action where you would do if/else check and redirect to correct path.

# routes.rb
root 'static_pages#home'

# StaticPagesController.rb
before_filter :redirect_if_logged_in

def redirect_if_logged_in
    redirect_to(user_path(@user)) if @user # check if user logged in
end

或者在 users#show 操作中做类似的事情.哪个最适合您的情况.

Or do similar in users#show action. Whichever suits your case best.

这篇关于不使用 Devise 为登录用户指定不同的根路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆