Back before named routes we used to say things like:
<%= link_to_if message.user, 'Poster', :controller => 'users',
:action => 'show', :id => message.user %>
This would make the text “Poster” only link if message has a user. But
with named routes this has become more complicated. Our first try is
<%= link_to_if message.user, 'Poster', user_path(message.user) %>
Although this looks nice it causes an error since the path is generated
prior to the condition not after the condition like using a hash is done.
To get around this problem I have found two solutions:
If you are linking to the “show” path then you can just pass the
object. This will force the path to not be generated until after the
condition (like a hash is done). For example:
<%= link_to_if message.user, 'Poster', message.user %>
The previous workaround works great if you want to link to the show action.
But what if you want to link to another action (say the edit action). In
this case the best way I have found is to use the hash_for* helpers
generated with the routing resource. So:
<%= link_to message.user, 'Poster',
hash_for_edit_user_path(:id => message.user) %>
A little more awkward than the previous workaround but it is the best I can
come up with. Any other suggestions (other than going back to manually
typing the hash)?