How to fix bad url generation when you are using url_for inside a nested controller

Problem:

I have a nested resource, say: members/:member_id/timelines/:id Inside my nested controller (timelines_controller) I use:

url_for(:controller =>'patients', :action => 'view', :id=> @patient.id)

The url generator decides that since I am nested inside ‘members’ I want my url to look like this: members/patients/:id

In fact, no I do not want my url to look like that. That url does not work. Do not want.

Solution:

You can tell url_for to not shove that members prefix in front, like this:

url_for(:controller =>'/patients', :action => 'view', :id=> @patient.id) 

Wait, did you see that? Looks the same, right?

It’s all about the forward slash, people. When you put a forward slash in front of the controller name, url_for will treat you right. Does the Rails documentation for url_for tell you this? No, it does not. This guy mentions it, though he’s not my original source for the fix, which I can’t find again (sorry, original source). With luck, one more blog post on the subject will make it easier for others to google the answer fast.

That’s all, folks. Little problem, little solution. Yay.