In this quick little article, I’ll assume that you already know about map.resources and RESTful routing support that’s now included in Edge Rails. If you need some background, head over and check out Ryan Daigle, who keeps up to date on Edge Rails and has a great introduction to RESTful routing.

But did you know that you can nest resources? Suppose you have comments, which belong to articles, which belong to topics. You’d like your URL string to be /topics/123/articles/456/comments

Easy. Just put this in your routes.rb file:


  map.resources :topics do |topic|
    topic.resources :articles do |article|
      article.resources :comments
    end
  end

This will produce the following routes:


comments_url(topic.id, article.id)
#=> /topics/:topic_id/articles/:article_id/comments/

articles_url(topic_id)
#=> /topics/topic_id/articles

article_url(topic_id, article_id)
#=> /topics/topic_id/articles/article_id

... and so on (the list is pretty long). If you’re exploring RESTful routing, I recommend the Routing Navigator plugin, which lets you explore all the routes in your application. The routing table above was generated by Routing Navigator.

Warning! Messing with your routes.rb file is one of the quickest ways to mess up your Rails app. Make sure you have a backup before you start doing this. You are using, Subversion, right?

Links


2 Responses to “Nested Routes Using Map.Resources”

  1. Jon Maddox Says:
    It's all about the nested routing. This is one of the things that had me totally confused about RESTful rails. Once you get that you should be using nested routing for models that belong_to models, then everything else sort of falls into place and becomes clear.
  2. Ryan Says:
    Yeah RESTful routing has taken quite a bit of getting used to. Especially since documentation is still so sparse. But it's getting better - "Agile Web Development With Rails 2nd Edition":http://www.pragmaticprogrammer.com/titles/rails2/index.html now has a whole section about map.resources and RESTful routing. Great book, highly recommended. Get the beta book.

Sorry, comments are closed for this article.