ActsAsNestedController with infinitely more documentation!

Posted by Peter Wagenet Sat, 25 Apr 2009 21:59:00 GMT

A while back I wrote a plugin to help with managing the logic of controllers with nested routes. Unfortunately, I was lazy and never documented it. I finally got around to refactoring it and adding proper documentation. You can find it at: http://github.com/rxcfc/acts_as_nested_controller

Path Expander

Posted by Peter Wagenet Sat, 07 Mar 2009 21:05:00 GMT

UPDATE: This is not necessary. See this post for details.

From time to time, I’ve been working on a Rails app with nested routes and ran into the situation where I want to nest the url only if I have the necessary information. Consider the following example to see what I mean:

user_projects_path(current_user) #=> /users/:id/projects

Now this will work perfectly if current_user is defined, but what if current_user is nil? Unfortunately, I’ll end up with the less than desirable “/users//projects”. To avoid this I could use an if statement along the lines of:

current_user ? user_projects_path(current_user) : projects_path
#=> /users/:id/projects or /projects

This will work of course, but it isn’t all that elegant. Another option would be something along the lines of:

projects_path(:user_id => current_user.id)

This solution will also work and has the benefit of being concise. Unfortunately we lose the nice route formatting. Instead of “/users/:id/projects”, we get “/projects?user_id=:id”. Not the prettiest result.

So I started thinking, wouldn’t it be great if Rails would automatically expand that path into “/users/:id/projects” if possible and if not just fall back to “/projects”. I started hacking around a bit and this is what I came up with:

The biggest downside to this is the call to #recognize_path. From my understanding, this can be a bit computationally intensive, so if you’re worried about top notch performance, this solution may be a bit risky.

So have you dealt with this before? If so, have you been able to come up with a better solution than this?