Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book