我一直在尝试使用Rails,但发现自己遇到了一个非常简单的问题:我有两个模型,幸存者和位置,它们是在route.rb中嵌套的资源。
Rails.application.routes.draw do
namespace 'api' do
namespace 'v1' do
resources :survivors do
resources :locations
end
resources :abduction_reports
end
end
end
这给了我几乎所有我需要的路线。问题在于幸存者和位置是一对一的关联,因此,如果我想更新幸存者的位置,那么端点是否为
PUT /survivors/:survivor_id/location
要解决此问题,我这样做:
Rails.application.routes.draw do
namespace 'api' do
namespace 'v1' do
[...]
put 'survivors/:survivor_id/location', to: 'locations#update'
end
end
end
但这似乎不是正确的方法...我的意思是,它可以在'resources:survivors do ... end'范围内定义吗?
我可能已经在Rails文档中看到了,但是我想我还没有意识到如何使文档示例适应我的问题。
答案 0 :(得分:0)
对于单个资源,请使用resource
宏:
Rails.application.routes.draw do
namespace 'api' do
namespace 'v1' do
resources :survivors do
resource :location
end
resources :abduction_reports
end
end
end
Prefix Verb URI Pattern Controller#Action
api_v1_survivor_location POST /api/v1/survivors/:survivor_id/location(.:format) api/v1/locations#create
new_api_v1_survivor_location GET /api/v1/survivors/:survivor_id/location/new(.:format) api/v1/locations#new
edit_api_v1_survivor_location GET /api/v1/survivors/:survivor_id/location/edit(.:format) api/v1/locations#edit
GET /api/v1/survivors/:survivor_id/location(.:format) api/v1/locations#show
PATCH /api/v1/survivors/:survivor_id/location(.:format) api/v1/locations#update
PUT /api/v1/survivors/:survivor_id/location(.:format) api/v1/locations#update
DELETE /api/v1/survivors/:survivor_id/location(.:format) api/v1/locations#destroy
api_v1_survivors GET /api/v1/survivors(.:format) api/v1/survivors#index
POST /api/v1/survivors(.:format) api/v1/survivors#create
new_api_v1_survivor GET /api/v1/survivors/new(.:format) api/v1/survivors#new
edit_api_v1_survivor GET /api/v1/survivors/:id/edit(.:format) api/v1/survivors#edit
api_v1_survivor GET /api/v1/survivors/:id(.:format) api/v1/survivors#show
PATCH /api/v1/survivors/:id(.:format) api/v1/survivors#update
PUT /api/v1/survivors/:id(.:format) api/v1/survivors#update
DELETE /api/v1/survivors/:id(.:format) api/v1/survivors#destroy
请参阅: