Musings from an east coast software developer, writer and reader.

From the Blog

Dec
02

Vanity URL Helpers in Rails

Posted by JB on December 2nd, 2010 at 11:36 pm

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.

Leave a Reply

3 Responses to Vanity URL Helpers in Rails

  1.  

    |