How to structure authenticated routes when using Devise?

前端 未结 2 1549
庸人自扰
庸人自扰 2021-01-16 02:18

In my question How to have root view when user is not logged in rails? max answered that we can use authenticated to make routes available only when someone is

2条回答
  •  清酒与你
    2021-01-16 02:59

    If you want to limit access to subjects you should do it on the controller layer - not in the routes. Using before_action :authenticate_user! will give a 401 Unauthorized response and redirect to the sign in.

    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
    

    Using the authenticated and unauthenticated route helpers are useful when you want the have different responses for the same route for authenticated and unauthenticated users but is not how you should structure your application.

    If you simply use authenticated in your routes unauthenticated users will get a 404 Not Found response instead of being prompted to sign in. Which is not helpful.

    Also resources :students, only: [:get] does not generate any routes at all. The onlyoption is for limiting the actions (show, index, edit, update ...) not the HTTP method. Use rake routes to see the routes in your app.

提交回复
热议问题