我在rails中有這條路線,我制作的其他開發人員
namespace :api do
namespace :v1 do
resources :articles do
resources :posts
end
end
end
現在我想通過郵遞員對其進行測驗,但我不明白端點的 url 將如何
我測驗了這個網址
http://localhost:3000/api/v1/articles?id=1&posts=1
但只是我收到了這個錯誤
"#<ActionController::RoutingError: uninitialized constant Api::V1::ArticlesController\n\n
uj5u.com熱心網友回復:
您可以鍵入rails routes
以列印您迄今為止定義的所有路線。然后你就會知道路由 URL 應該是什么樣子
在您的示例中,它應該類似于GET api/v1/articles/1/posts/1
.
uj5u.com熱心網友回復:
您可以打開localhost:3000/routes
以查看和搜索您的路線助手路徑和網址
uj5u.com熱心網友回復:
當您在 Rails 中嵌套路由時,“父”資源作為靜態段和由父 ID 組成的動態段添加到路徑中:
/api/v1/articles/:article_id/posts/:id
rails routes
您可以使用命令在應用程式中顯示路線,也可以http://localhost:3000/routes
在較新版本的 Rails 中訪問。
這基本上是與傳入請求 URI 匹配的類固醇上的正則運算式。
查詢字串引數不用于匹配路由,這就是http://localhost:3000/api/v1/articles?id=1&posts=1
路由到 的原因,ArticlesController#index
因為它匹配/api/v1/articles
。
一般來說,Rails 風格的 REST查詢字串引數僅用于附加資訊,例如分頁或過濾。不適用于路由到資源。
如果您想將其宣告為淺路徑,則將shallow
選項傳遞給resources
宏:
namespace :api do
namespace :v1 do
resources :articles do
resources :posts, shallow: true
end
end
end
/api/v1/posts/:id
這將為單個帖子生成成員路由,而集合路由(新建、索引、創建)仍然嵌套。
max@maxbook ~/p/sandbox_7 (main)> rails routes | grep posts
api_v1_article_posts GET /api/v1/articles/:article_id/posts(.:format) api/v1/posts#index
POST /api/v1/articles/:article_id/posts(.:format) api/v1/posts#create
new_api_v1_article_post GET /api/v1/articles/:article_id/posts/new(.:format) api/v1/posts#new
edit_api_v1_post GET /api/v1/posts/:id/edit(.:format) api/v1/posts#edit
api_v1_post GET /api/v1/posts/:id(.:format) api/v1/posts#show
PATCH /api/v1/posts/:id(.:format) api/v1/posts#update
PUT /api/v1/posts/:id(.:format) api/v1/posts#update
DELETE /api/v1/posts/:id(.:format) api/v1/posts#destroy
此選項也是“繼承的”,因此您可以將其傳遞給父資源以使所有嵌套路由變淺:
namespace :api do
namespace :v1 do
resources :articles, shallow: true do
resources :posts
resources :photos
resources :videos
end
end
end
uj5u.com熱心網友回復:
該錯誤表明您尚未創建與路由對應的控制器。
檔案夾結構:
app/controllers/api/v1/posts_controller.rb
class Api::V1::PostsController
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524646.html
標籤:轨道上的红宝石
上一篇:Rails7:我想將代碼放在/lib/中,而不是撰寫gem,但我得到NoMethodError
下一篇:創建時未保存1個引數