且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不使用 Devise 为登录用户指定不同的根路径

更新时间:2023-10-28 17:23:16

我认为在路由文件中使用 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.