繁体   English   中英

Rails 3 w / Devise:如何根据用户是否经过身份验证设置两个单独的主页?

[英]Rails 3 w/ Devise: How to set two separate homepages based on whether the user is authenticated or not?

我正在使用Rails 3和Devise创建一个应用程序,用户可以访问该网站并显示包含登录和注册表单的主页。 这个页面有自己的控制器(“主页”),所以它的路线是

root :to => "homepage#index"

如果用户已经登录,我想显示不同的主页。这将考虑到根点

root :to => "dashboard#index"

有没有办法在routes.rb中设置条件路由,这样我就可以在将用户路由到其中一个主页之前检查用户是否经过身份验证?

我尝试使用以下代码,但如果我没有登录,设计要求我登录,所以显然只有第一条路线有效。

authenticate :user do
  root :to => "dashboard#index"
end
  root :to => "homepage#index"

此外,我希望网址在两种情况下都指向www.example.com,以便www.example.com/dashboard/index和www.example.com/homepage/index永远不会出现在浏览器中。

太感谢了 !!!

试试这个,它特定于Warden / Devise。

root to: "dashboard#index", constraints: lambda { |r| r.env["warden"].authenticate? }
root to: "homepage#index"

在您的HomeController中:

def index
  if !user_signed_in?
    redirect_to :controller=>'dashboard', :action => 'index'
  end
end

(在这里回答完全相同的问题: https//stackoverflow.com/a/16233831/930038 。在这里添加答案也可供其他人参考。)

在您的routes.rb

authenticated do
  root :to => 'dashboard#index'
end

root :to => 'homepage#index'

这将确保所有经过身份验证的用户的root_urldashboard#index root_url

供您参考: https//github.com/plataformatec/devise/pull/1147

这是rails 4的正确答案

root to: 'dashboard#index', constraints: -> (r) { r.env["warden"].authenticate? },
         as: :authenticated_root
root to: 'homepage#index'

我试图将此添加到/编辑已接受的答案,但显然是接受了太多的编辑。 无论如何,投票支持接受的答案(来自布拉德利),它帮助我想出了这一个:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM