views:

28

answers:

1

I have been using the following route successfully in my Rails 2.x application:

map.user ':id', :controller => 'users', :action => 'show'

This, as my lowest route, properly catches things like /tsmango and renders Users#show.

I'm now trying to add a second, similar route like:

map.post '~:id', :controller => 'posts', :action => 'show'

Because neither my users or my posts are allowed to contain ~ and because this route will appear above my map.user route, I assumed this would properly catch any call starting with /~ and render my Posts#show action. Unfortunately, I'm having trouble getting this one to work.

What's interesting is that this similar route works perfectly:

map.post ':id~', :controller => 'posts', :action => 'show'

Although, I'm certainly willing to go with ':id~' since it has the same result, at this point I'm really just frustrated and curious as to how you would build a route that matches '~:id'.

It's worth mentioning that I do not want to modify my to_param method or my actual user and post slugs to include the prepended ~. I just want that in a route to indicate which action should handle it. Unless I'm mistaken, this rules out the use of something like:

:requirements => {:id => /\~[a-zA-Z0-9]/}

Thanks, in advance, for any help you can provide!

Update: I'm aware of route priority and stated above that I am placing the '~:id' route above the ':id' route. I receive the following error while trying to generate the url like post_path(@post):

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.to_sym
+1  A: 

Routes are prioritized depending of the order in which they're declared.
When you define first the :id route, the second one is never executed.

In order for this to work, you just have to first define the ~:id route and then the :id one.

map.post '~:id', :controller => 'posts', :action => 'show'
map.post ':id',  :controller => 'users', :action => 'show'
Damien MATHIEU
Yep, I know they are prioritized. I mentioned above that I'm placing the '~:id' route above the ':id' route, but I'm still unable to make that work.I'm receiving this error: You have a nil object when you didn't expect it! The error occurred while evaluating nil.to_symWhen I try and use the route like: link_to('Test', post_path(@post))
tsmango