6.4. Nested Resources

What you'll need to address all these points is the ability to nest the two resources. Edit your config\routes.rb file to replace the following two lines (non-adjacent in your routes file):

map.resources :comments
map.resources :articles, :collection => { :unpublished => :get }


map.resources :articles, :has_many => :comments, :collection => { :unpublished =>
:get }

Alternatively, when you need more control, you can use this equivalent block-based syntax:

map.resources :articles, :collection => {:unpublished => :get} do |article|
  article.resources :comments

Once you've added the highlighted line to the routes file, run rake routes again and you'll see that all the /comments are gone, replaced by /articles/:article_id/comments. Awesome!

On top of that, you'll have _path and _url helpers, as you're accustomed to, for comments as well. Given that the routes are nested, the stem for these methods will be different, as shown in the output of the routes task you just ran. For example, article_comments_url will accept an article as an argument and return the URL to access a list of all its comments. If you hadn't nested the resources, that helper would have been comments_url, and it wouldn't have accepted any arguments.

You changed the routes file, so go ahead and restart Mongrel. The bad news is that if you try to load http://localhost:3000/articles/1/comments/new in your browser, you will get a nasty error like this one:

undefined method 'comments_path' ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.