我创建了一个rails api,我希望资源位于/api/v1/
路由下,包括注册和身份验证。
我创建了以下路线,为我提供了Devise所需的路线:
config/routes.rb
namespace :api, defaults: { format: :json } do
namespace :v1 do
devise_for :users, as: 'api'
end
end
它提供:
Prefix Verb URI Pattern Controller#Action
new_api_user_session GET /api/v1/users/sign_in(.:format) api/v1/sessions#new {:format=>:json}
api_user_session POST /api/v1/users/sign_in(.:format) api/v1/sessions#create {:format=>:json}
destroy_api_user_session DELETE /api/v1/users/sign_out(.:format) api/v1/sessions#destroy {:format=>:json}
cancel_api_user_registration GET /api/v1/users/cancel(.:format) api/v1/registrations#cancel {:format=>:json}
new_api_user_registration GET /api/v1/users/sign_up(.:format) api/v1/registrations#new {:format=>:json}
edit_api_user_registration GET /api/v1/users/edit(.:format) api/v1/registrations#edit {:format=>:json}
api_user_registration PATCH /api/v1/users(.:format) api/v1/registrations#update {:format=>:json}
PUT /api/v1/users(.:format) api/v1/registrations#update {:format=>:json}
DELETE /api/v1/users(.:format) api/v1/registrations#destroy {:format=>:json}
POST /api/v1/users(.:format) api/v1/registrations#create {:format=>:json}
但是,当我尝试注册用户时,我收到以下错误
ActionController::RoutingError:
uninitialized constant Api::V1::RegistrationsController
答案 0 :(得分:3)
为了将资源保持在/api/v1/
路径下并且仍然可以使用设备的默认控制器,需要修复路由。
不使用namespace
,而是使用scope
。
scope :api, defaults: { format: :json } do
scope :v1 do
devise_for :users
end
end
这样您甚至不必使用as: 'api'
来识别您的资源
Prefix Verb URI Pattern Controller#Action
new_user_session GET /api/v1/users/sign_in(.:format) devise/sessions#new {:format=>:json}
user_session POST /api/v1/users/sign_in(.:format) devise/sessions#create {:format=>:json}
destroy_user_session DELETE /api/v1/users/sign_out(.:format) devise/sessions#destroy {:format=>:json}
cancel_user_registration GET /api/v1/users/cancel(.:format) devise/registrations#cancel {:format=>:json}
new_user_registration GET /api/v1/users/sign_up(.:format) devise/registrations#new {:format=>:json}
edit_user_registration GET /api/v1/users/edit(.:format) devise/registrations#edit {:format=>:json}
user_registration PATCH /api/v1/users(.:format) devise/registrations#update {:format=>:json}
PUT /api/v1/users(.:format) devise/registrations#update {:format=>:json}
DELETE /api/v1/users(.:format) devise/registrations#destroy {:format=>:json}
POST /api/v1/users(.:format) devise/registrations#create {:format=>:json}