如何在使用Devise时构建经过身份validation的路由?
在我的问题中如何在用户未登录rails时拥有根视图? max回答我们可以使用authenticated
来使路由仅在有人通过身份validation时可用。 我正在探讨如何构建这个:
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
问题是我不想允许任何未经validation的操作:subjects
如何阻止?
如果要限制对主题的访问,则应在控制器层上进行 – 而不是在路径中。 使用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
当您希望对经过身份validation和未经身份validation的用户具有相同路由的不同响应时,使用经过authenticated
和unauthenticated
authenticated
unauthenticated
路由助手非常有用,但不是应该如何构建应用程序。
如果您只是在路由中使用经过authenticated
未经authenticated
validation的用户将获得404 Not Found响应而不是提示您登录。这没有用。
resources :students, only: [:get]
根本不生成任何路线。 only
选择是限制操作(显示,索引,编辑,更新......)而不是HTTP方法。 使用rake routes
查看应用中的路线。
以下是构建经过身份validation和未经身份validation的路由的简单方法。
在app / controllers / application_controller.rb中,添加"before_action :authenticate_user!"
。
我的app / controllers / application_controller.rb文件:
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! end
我的config / routes.rb:
Rails.application.routes.draw do devise_for :users root "home#index" devise_for :users, controllers: { :sessions => "users/sessions", :registrations => "users/registrations" } authenticated :user do resources :students end unauthenticated :user do #Some route end end