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
