Building Dynamic Navigation Bar Elements in Rails
In this guide we're going to walk through how to create a dynamic navigation bar the renders different tabs to users based on their role.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we're going to walk through how to create a dynamic navigation bar the renders different tabs to users based on their role.

If you look at the application, right now we have a link called Admin Dashboard which is listed in the Account drop down menu. Right now the link doesn't go anywhere. In this guide we'll point this to the admin dashboard and also hide it from non admin users.

Let's start by opening the partial called _nav.html.erb, and here you'll see the link called Admin dashboard. We're going to use a temporary if statement to check if an admin is logged in, and if they are it will render the dashboard link.

<!-- app/views/shared/_nav.html.erb -->

<% if current_user.try(:type) == 'AdminUser' %>
  <li>
    <%= link_to "Admin Dashboard", admin_root_path %>
  </li>
  <li class="divider"></li>
<% end %>

If you refresh the browser, you can see the link if you're logged in as an admin user. However, the browser will throw an error if you click the Logout button because the application is assuming that there is a current user, even when no one is logged in.

large

To fix this, let's place an if statement at the beginning of the navigation bar. This means that if no user is signed in, then the entire navigation bar will not be visible (which is really ideal anyways).

Now if you test this in the browser, everything should now be working properly.

Eventually we're going to refactor this code since the view code is a bit convoluted for my taste. But for right now it's fine.

Before we wrap up, I want to change the word Account to Options.

The full _nav partial code is placed below:

<!-- app/views/shared/_nav.html.erb -->

<div class='logo'>
  <h1>Time Tracker</h1>
</div>

<% if current_user %>
  <ul class="custom-nav nav nav-tabs">
    <li class="<%= active?(root_path) %>">
      <%= link_to "Home", root_path %>
    </li>
    <li class="<%= active?(posts_path) %>">
      <%= link_to "Time Entries", posts_path %>
    </li>
    <li class="<%= active?(new_post_path) %>">
      <%= link_to "Add New Entry", new_post_path, id: 'new_post_from_nav' %>
    </li>
    <li class="dropdown pull-right">
       <a href="#" data-toggle="dropdown" class="dropdown-toggle">Options<strong class="caret"></strong></a>
      <ul class="dropdown-menu">

        <% if current_user.try(:type) == 'AdminUser' %>
          <li>
            <%= link_to "Admin Dashboard", admin_root_path %>
          </li>
          <li class="divider"></li>
        <% end %>

        <li>
          <%= link_to "Logout", destroy_user_session_path, method: :delete %>
        </li>
      </ul>
    </li>
  </ul>
<% end %>

Resources