【问题标题】:Check the cookies/session in the routes.rb file检查 routes.rb 文件中的 cookie/会话
【发布时间】:2014-05-05 15:29:08
【问题描述】:

我想根据 cookie/会话设置根。如果用户已经登录,我想检查 cookie/会话并相应地呈现一个不同的页面作为根 url。

我想做这样的事情

if (cookie with userID) do
   root 'user/index'
else
   root 'welcome/index'
end

有没有一种方法可以访问 ApplicationController 或类似的东西,以便我可以检查所有内容?

谢谢

【问题讨论】:

    标签: ruby-on-rails session cookies authentication


    【解决方案1】:

    我认为您应该在这里使用不同的方法。例如,您可以始终将根路径映射到相同的操作,并将所有逻辑放入该操作:

    class UsersController < ApplicationController
      def index
        redirect_to welcome_path and return unless logged_in?
        ... # rest of your code here 
      end
    end
    

    注意:假设logged_in? 是从会话中加载当前用户或返回 nil 的方法。

    将这种逻辑移动到before_filter(在Rails4中before_action)可能是个好主意:

    class UsersController < ApplicationController
      before_filter :require_login
    
      def index
      end
    
      private
    
      def require_login
        redirect_to welcome_path unless logged_in?
      end
    end
    

    如果您的大部分应用程序(控制器范围)依赖于已登录的用户,请将其移至 ApplicationController(过滤器将针对每个请求运行)。在没有此要求的特定情况下,您可以使用skip_before_filter :require_login 跳过它。

    顺便说一句,如果你想通过你的路线来实现它,你可以玩constraintsdoc here)。示例代码:

    YourApp::Application.routes.draw do
      root 'users#index', constraints: lambda { |request| request.session['user_id'].present? }
      root 'welcome#index'
    end
    

    这个问题的更多想法:How can I redirect a user's home (root) path based on their role using Devise?

    【讨论】:

    • 直接放到ApplicationController中这样每次都调用会不会好点?
    • 如果您的大部分应用程序(控制器)依赖于登录用户,是的!然后,对于特定情况,您可以使用skip_before_filter :require_login 跳过它。
    • 太棒了!非常感谢!
    • 不客气@ConstantinJacob。我刚刚用更多想法更新了答案。请记住,接受和投票(如果您认为合适的话)答案对社区很有用:)
    • 我会的。我仍在努力使第一个解决方案发挥作用……有点困难。但我不想使用任何宝石。我想自己做!
    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多