[edge Rails] shallow nesting of routes
Ok, finally. This is the first post of a series about some new exciting edge rails features. ;)
Here at Railslove most of our projects are living on the edge (thanks to braid!) ;) and we try to keep close track of what’s happening in the rails master branch.
Today I’ve found a commit that is actually a few days old but this will clean up a lot of my nested routes.
Imagine your application has a User who has_many :posts which again has_many :comments. Your routes would look something like:
map.resources :users do |user| user.resources :posts do |post| post.resources :comments end end
This defines the following helpers and URLs
users_url #=> /users/ user_posts_url #=> /users/1/posts/ user_post_comments_url #=> /users/1/posts/10/comments
however only the full nested routes are available.
/posts/10 or /comments/10 are not available and you need to declare those seperately:
map.resources :posts do |post| post.resources :comments end map.resources :comments
This commit now allows you to add a :shallow => true option which does this automatically for you. This is great and shortens the routes.rb a lot.
The example above would then just look like:
map.resources :users, :shallow => true do |user| user.resources :posts, :shallow => true do |post| post.resources :comments end end
and post_url, comment_url, post_comments_url,… get also defined.
very nice!
Have a look at the commit message and source code for more information.
Update:
Georg of SalesKing.eu fame pointed me to Ryan’s great post about the :shallow option.
Comments
2 Responses to “[edge Rails] shallow nesting of routes”
Yes, really nice feature. Do you know Ryan Daigle’s periodic writings about “What’s new in Edge Rails”? He has written about shallow routes a few days ago, and there is more to read about other interesting Rails commits on his website: http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes
Hi Georg,
thanks for the note. I’ve added the link to the post.
Ryan’s “What’s new in edge rails” is pretty awesome.