Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

View Profile Link

So as of right now I am trying to link to the user's profile I currently have something like this:

<li><%= link_to "View Profile", profiles_show_path %></li>

This code when clicked on shows domain.com/profiles/show and I want it to display domain.com/USERNAME

My routes.rb is this:

get '/:id' to: 'profiles#show'

4 Answers

Actually, a much better way would be to change the route to:

get '/:id', to "profiles#show", as: :profile_show

Also, notice in the routes file, you do not add path. You can run "rake routes" in the terminal to see what all your routes map to. Then, when you link to it:

<li><%= link_to "View Profile", profile_show_path(@user) %></li>

This is the rails way of doing it. Notice I have the @user instance variable. You need to change that to whatever instance variable is storing the user for that view. (Maybe it's something like @post.user if you are on the Post page or something).

I also recommend you store your user pages under "users". What if someone takes a username that also is also the name of one of your models? Let's say you have the model forum, so mydomain.com/forum goes to your forum. Someone else decides to be username forum. You're going to get routing errors here.

What I did was put it under "users", so:

get 'users/:id' to: 'profiles#show', as: :profile_show

So then there would be two different routes:

  • mydomain.com/forum -> goes to the forum
  • mydomain.com/users/forum -> goes to that users profile page

Hope that all makes sense.

You can do:

<%= link_to "View Profile", "/#{current_user.profile_name}" %>

Min-Zaw Mra Thank you very much for that, much appreciated!

Thanks for the info, Brandon Barrette. I have seen the method calls having the form profile_show_path(@user) in some of the code generated by devise before and wasn't entirely sure how that worked but this was a really good example.

As for you advice on storing the user pages under 'users,' I understand your point completely. It is, however, common to see sites displaying example.com/username. If that is to be allowed, is reserving the user names the only way to overcome the routing errors in case some users try to take the name of the existing models?