检查routes.rb文件中的cookie / session

时间:2014-05-05 15:29:08

标签: ruby-on-rails session cookies authentication

我想根据cookie / session设置root。如果用户已经插入,我想检查cookie /会话并相应地呈现不同的页面作为根URL。

我想做这样的事情

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

有没有办法可以访问ApplicationController或类似的东西,以便我可以查看所有内容?

由于

1 个答案:

答案 0 :(得分:3)

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

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?