2017-04-16 10 views
0

私の質問ではHow to have root view when user is not logged in rails?は、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オプションは、HTTPメソッドではなく、アクション(show、index、edit、update ...)を制限するためのものです。アプリ内のルートを確認するにはrake routesを使用してください。

関連する問題