我有這個資源樹:嵌套資源 - 如何避免冗餘路由?
- 論壇
- 主題
- 後
- 主題
我希望能夠獨立訪問它們儘可能。我想避免像/forum/:forum_id/topic/:topic_id/post/:id
這樣的冗餘路由,因爲我只能做/post/:id
。
理想的路線是這樣的:
/forums => Forums#index # Lists every forum
/forum/new => Forums#new # New forum
/forum/edit => Forums#edit # Edit forum
/forum/:id => Forums#show # Shows forum
/forum/:id/forums Forums#index # Lists nested forums
/forum/:id/topics => Topics#index # Lists topics inside forum
/forum/:id/topic/new => Topics#new # New topic
/topics => Topics#index # Lists every topic
/topic/:id => Topics#show # Shows topic
/topic/:id/posts => Posts#index # Lists posts inside topic
/topic/:id/post/new => Posts#new # New post
/posts => Posts#index # Lists every post
/post/:id => Posts#show # Shows post
什麼對這樣的情況進行建模的最佳方式?
這裏是我的嘗試:
resources :forums
resources :topics
resources :posts
resources :forums do
resources :topics
end
resources :topics do
resources :posts
end
的問題是,這些設置創造了很多無用的航線,如:
/forums/:forum_id/topic/:id # Redundant - /topic/:id
/topics/:topic_id/post/:id # Redundant - /post/:id
/topics/new # No current forum
/posts/new # No current topic
有什麼辦法來指定要創建哪些路線?
在控制器中,我該如何處理映射到同一動作的多個路由?例如,在Topics#index
裏面我怎麼知道我是否應該處理GET /forum/:id/topics
或GET /topics
?