嵌套资源
很多时候资源还会包含一组别的资源。譬如说,我们可能允许别人给文章做评论,这时每个评论也
会是一项资源,评论的集合则关联到“文章”资源。
对于这种情况,Rails 提供了一种便捷而直观的方式来声明路由:
Download restful2/config/routes.rb
ActionController::Routing::Routes.draw do |map|
→ map.resources :articles do |article|
→ article.resources :comments
end
# ...
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
更为简洁和常见写法如下:
map.resources :articles, :has_many => :comments
map.resources :articles, :shallow => true do |article|
article.resources :comments
end
这样就可以识别出下列路由:
/articles/1 => article_path(1)
/articles/1/comments => article_comments_path(1)
/comments/2 => comment_path(2)