O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 }

with:

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
end

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' ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required