例如,我在“ / api”下有一些路线:
/api/users
/api/users/new
/api/users/:id/edit
在UsersController
中,所有方法均以JSON响应,并且其行为类似于API系统。
我想在/api
名称空间下添加另一条路由-如/api/auth/index
我添加了新的resources
,但无效
这是我的路线。rb:
Rails.application.routes.draw do
devise_for :users
root to: "pages#root"
namespace :api do
resources :user, only: %i[index show create destroy update search]
post '/user/import', to: 'user#import_line'
resources :auths, only: %i[index]
end
get '*path', to: 'pages#root'
end
如何在api
名称空间下添加新路由?
答案 0 :(得分:0)
您应该使用resources :users
而不是:user
。宁静的路线大部分应为复数*。如果有不止一个,则应始终使用复数形式。
namespace :api do
resources :users, only: %i[index show create destroy update]
end
这似乎无关紧要,但是由于关于rails的配置特性的约定,这将使您感到非常悲伤,因为它不能与多态路由助手一起正常工作。控制器的名称也应为复数(Api::UsersController
)。
要向add additional restful actions传递一个块到resources
:
namespace :api do
resources :users, only: %i[index show create destroy update] do
get :search
post :import, on: :collection, action: :import_line
end
end
如何在api名称空间下添加新路由?
通过将它们放置在您传递给namespace
的块中:
namespace :api do
resources :users, only: %i[index show create destroy update] do
get :search
post :import, on: :collection
end
resources :auths, only: [:index]
end
但是,这将创建GET /auths
而不是GET /auths/index
。我建议您阅读rails guides on how the rails conventions handle restful routing。
答案 1 :(得分:-1)
删除您的%i,然后像下面这样写,它对我有用。
namespace :api do
resources :auths, only: [:index]
end