ruby-on-railserbmenu-items

How can I hide or remove a menu item?


I have the following snippet of code that creates a list of navigation items (a menu):

<ul class="nav">
  <li><%= link_to "Log in", login_path %></li>
  <li><%= link_to "Help", help_path %></li>
  <% if logged_in? %>
  <li><%= link_to "Home", root_path %></li>
</ul>

When I am not logged in, the menu shows as:

Log in Help

When I do log in, it shows as

Log in Help Home

After logging in, I'd like to:

  1. hide or remove the log in menu item and
  2. rearrange the remainder menu items so that Home is first and Help is next.

Solution

  • You just need to arrange them properly and use the condition properly

    <ul class="nav">
      <% if logged_in? %>
        <li><%= link_to "Home", root_path %></li>
      <% else %>
        <li><%= link_to "Log in", login_path %></li>
      <% end %>
      <li><%= link_to "Help", help_path %></li>
    </ul>
    

    Explanation:

    The first if-else checks for a logged in user and will return the <li> Home if logged in or Log in If not logged in

    The last <li> will always be displayed no matter user is logged in or not