I have been doing some hacking on Type Aloud and I was looking for an answer to a question that was bugging me: what is the best way to use link_to with a vanity URL setup? I asked my question over at Stack Overflow and I figured I would post the answer to the question here in case anyone was looking as I was.
Inside of my application the route setup is quite simple.
match '/:id', :to => "users#show" match '/:user_id/:id', :to => "stories#display"
Now I want to be able to make a very simple call inside of my view logic which will print out a pretty URL. Since I am using resource definitions for several controllers I cannot use the normal Rails URL helpers. The answer to my question is actually quite simple, and I already have used it before, but what I wasn’t doing was correctly passing through the objects into the helper. Here are the changes that you need to make to those routes above.
match '/:id', :to => "users#show", :as => "vanity_show_user" match '/:user_id/:id', :to => "stories#display", :as => "vanity_show_users_story"
And finally inside of your view you would build both links like the following.
<%= link_to @story.name, vanity_show_users_story_path(@user, @story) %> <%= link_to @user.name, vanity_show_user_path(@user) %>
I hope that this helped you out as much as it helped me! Kudos to the amazing Ryan Bigg for the original answer.
|
Ryan Bigg |
Hey! Glad I could help out
johnbellone |
Absolutely did! If you are ever in the NYC area I owe you several brews.
jb |
Thanks again, man. Whenever you’re in the New York City area I owe you several beers. Cheers!