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

Turn user name into a link directing to their profile?

How can I turn the user name into a link which redirects people to their profile? I was able to do it on my 'All Users' page however the same code does not work for my 'Explore' page which houses all users posts.

I would like to turn this line of code into a link redirecting people to the users profile page.

    <strong><%= post.user.name if post.user %></strong>

This is the code I used on my 'All Users' page however, it does not work for my index page.

  <% user = @post.user %>
  <p><strong><%= link_to(user.name, user_path(user)) if @post.user %></strong></p>

Post / Index

 <div class="page-header">
   <center><strong><h1> Explore Page </h1></strong></center>
 </div>

   <% if user_signed_in? %>
     <center><%= link_to 'New Post', new_post_path, class: "btn btn-danger btn-lg active" %></center>
   <% end %>  

   <div id="posts" class="transitions-enabled">
       <% @posts.each do |post| %>

    <div class="box panel panel-default">
      <%= link_to image_tag(post.image.url(:medium)), post %>
      <div class="panel-body">
      <%= post.description %><br/>
      <strong><%= post.user.name if post.user %></strong>

      <% if post.user == current_user %>
        <div class="actions">
        <%= link_to edit_post_path(post) do %>
        <span class="glyphicon glyphicon-edit"></span>
            Edit
          <% end %>
        <%= link_to post, method: :delete, data: { confirm: 'Are you sure?' } do %>
        <span class="glyphicon glyphicon-trash"></span>
            Delete
          <% end %>
        </div>
       <% end %>
     </div>
     </div> 
  <% end %>
 </div>


 <div class="center">
  <%= will_paginate @posts, renderer: BootstrapPagination::Rails %>
 </div>

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

I can't say for sure if I don't have your full code for testing on my machine, but I would try something like this:

<strong><%= link_to(post.user.name, user_path(post.user)) if post.user %></strong>

Thank you!! I tried something similar however, I forgot to add 'post' within the (post.user).