2017-04-16 16 views
0

在我的問題How to have root view when user is not logged in rails? max答覆我們可以使用authenticated使路由只有當有人被認證。我有一個probem,我怎麼可以構建這樣的:如何在使用Devise時構建認證路線?

Rails.application.routes.draw do 
    devise_for :users 


    authenticated :user do 
    # when authenticated allow all action on student 
    resources :subjects do 
     resources :students 
    end 
    end 

    # when not only allow read on student 
    resources :subjects do 
    resources :students, only: [:get] 
    end 

    root "home#index" 
end 

問題是我不想讓上:subjects任何未經驗證的行動如何制止呢?

回答

3

如果您想要限制對主題的訪問,您應該在控制器層上執行操作 - 而不是在路由中。使用before_action :authenticate_user!會給401 Unauthorized響應和重定向到的跡象。

class ApplicationController 
    # secure by default 
    before_action :authenticate_user!, unless: :devise_controller? 
end 

class SubjectsController < ApplicationController 
    # whitelist actions that should not require authentication 
    skip_before_action :authenticate_user!, only: [:show, :index] 
    # ... 
end 

Rails.application.routes.draw do 
    devise_for :users 

    resources :subjects do 
    resources :students 
    end 

    root "home#index" 
end 

使用,當你想要有同樣的路線不同的反應爲驗證的authenticatedunauthenticated路線助手是有用的,未經認證的用戶,但不是你應該如何構建你的應用程序。

如果您在路由中只使用authenticated,未經身份驗證的用戶將得到404 Not Found響應,而不是被提示登錄。這是沒有用的。

另外resources :students, only: [:get]根本不會生成任何路由。 only選項用於限制操作(show,index,edit,update ...)而不是HTTP方法。使用rake routes查看您應用中的路線。