Notebook

June 24, 2008 1:50PM

Organize Nested Resource Controllers More Efficiently in Rails

Nested resources are awesome. If you want to have a blog with entries that have comments, the resources are dead simple:

map.resources :entries do |entry|
  entry.resources :comments
end

Awesome, now you have set up paths like entries/3/ and entries/3/comments/ using an EntriesController and a CommentsController. What if, however, you want to have a base comments resource (/comments/) to show all comments? You already have a CommentsController, and it doesn't do what you want. To solve this, I do something like this:

map.resources :entries do |entry|
  entry.resources :comments, :controller => 'entries/comments'
end

map.resources :comments

Now, you have all your routes set up, and you can have separate controllers, Entries::CommentsController (which lives in controllers/entries/comments_controller.rb) and CommentsController. Just remember when generating the nested controller to use the proper name, like so:

ruby script/generate controller entries/comments

Did you like this entry? Make sure to subscribe to my RSS feed to keep up-to-date with my newest entries and links.

Comments

Leave a Comment

(required)

(required, never displayed)

(optional)

Ajax-loader