2015-06-21 34 views
2

很简单的问题,但我似乎无法找到一个好的谷歌的答案。Rails设计路线:如果用户登录,则指向索引。否则,指向新的用户会话

错误:

undefined method `user_signed_in?' for #<ActionDispatch::Routing::Mapper:0x007fc6369320e8> (NoMethodError) 

服务器甚至不会启动。

我的代码:

Rails.application.routes.draw do 

devise_for :users, :path_prefix => 'u' 
resources :users 

    devise_scope :user do 
    get "login", to: "devise/sessions#new", as: :login 
    get 'logout', to: 'devise/sessions#destroy', as: :logout 
    get 'user/edit', to: 'devise/registrations#edit', as: :change_password 
    end 

    resources :apps do 
    resources :elements, controller: 'apps/elements' 
    end 

    resources :elements do 
     resources :features, except: [:index], controller: 'apps/elements/features' 
    end 

if user_signed_in? 
    root to: 'apps#index' 
else 
devise_scope :user do 
    root to: 'devise/sessions#new' 
end 
end 

end 

什么是着手做这项工作的最佳方式是什么?我很想尝试解决这个问题,并使网站变得脆弱,成为一名新的RoR用户。提前致谢。

+0

你为什么不重定向您的控制器动作中的用户,而不是你的路由 – Cyzanfar

+0

这是一个很好的点。我只是认为路线是最简单的方法。我应该如何将它们重定向到设计新会话页面?到目前为止,我有'如果user_signed_in? <用户正在登录的代码> else redirect_to <我不知道该怎么放在这里>' – Nickdb93

回答

2

在Rails中,访问控制是在控制器层完成的,而不是在路由层。

路由只是为不同的参数集和请求URL定义匹配器。它们在rails开始处理请求之前被处理,他们不知道会话的任何内容。 Rails甚至可以使用YML来定义路由,除了Ruby在DSL方面更好。

如果你想要求用户已登录你可以使用:

class SomeController < ApplicationController 
    before_action :authenticate_user! # a Devise helper method 
end 
+1

哦,亲爱的主。你知道吗,我在过滤器前使用':authenticate_user!',但是当我在设计特性时,我把'except::index'放在了一起。我不能相信我只是忘了把它关掉,并且正在做各种各样的愚蠢的东西。感谢您清理它!现在,我再做一次愚蠢的举动之前还有更多的咖啡。 – Nickdb93

+0

我会说你的答案是有用的,但我是一个代表点远离能够。所以代替这一点,谢谢你们两位! – Nickdb93

+0

所以你必须在你的AppsController中设置'before_action'回调? – Cyzanfar

相关问题