views:

493

answers:

3

Premise: Usually during preparation of a new Ruby on Rails App, I draw out models and relations regarding user navigations. Usually I hit a place where I need to ask myself, whether or not I should go beyond the usual "rule of thumb" of nesting no more 1 level deep. Sometimes I feel the need to nest, rather than creating another namespace route and duplicating work.
Here's an example:

Models: User, Company, Location
User has and belongs to many Companies (many to many)
User has and belongs to many Locations (many to many)
Company has and belongs to many Locations (many to many)

Routes:
1 level nesting
users/:user_id/companies/ - list all companies related to a user
users/:user_id/locations/ - list all locations related to a user
more than 1 level nesting
users/:user_id/companies/:company_id/locations/ - list all company-locations of a user

So, my question is whether or not it is appropriate to nest more than 1 level deep in RoR? Yes or no? And why?

+6  A: 

I tend to follow Jamis Buck's advice and never nest more than one level deep.

Edit: If you are going to nest more than 1 level I would check out the new shallow routes feature in Edge

Mike Breen
Shallow routes FTW. That's almost certainly what you want. LocationsController#index makes no sense as /locations, because you'd never want /all/ the locations. But it lets you keep all the locations at /locations/<id> no matter which type it's associated with.
Otto
+1  A: 
users/:user_id/companies/:company_id/locations/

While technically this is fine, wouldn't the named route helper therefore be

user_company_location_path( user_id, company_id, location_id )

having to cart round 3 parameters like that is annoying. Anything annoying is probably a red flag.

Orion Edwards
check out smart_url in resource_controller: smart_url(@user, @company, @location). But yeah, nesting too deep seems wrong.
webmat
+1  A: 

Whilst it sounds good in theory, I've found nesting more than one level can start to get confusing - particularly if you have the same named controller at different levels (which can be quite common)

Eg

  user/x/blog/y/profile/z, and
  user/x/profile/a

I'll often find I'm working in a different namespace to what I think I'm working in. If they do similar, but different things, it can get quite confusing =)

My current app, I went thru last week and removed most of the nested routes. (Of course, YMMV)

Dave Smylie