-1

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.
pnuts
  • 58,317
  • 11
  • 87
  • 139
  • Maybe I'm unclear what you're asking, but why is hiding the "Log in" link more complicated than hiding the "Home" link, which you're already doing? If the "Home" link is only when you're logged in, and you want it shown before the "Help" link when you're logged in, just move it before the "Help" link. (I'm assuming the missing `end` tag is just a copy-pasta-to-SO error) – Simple Lime Jul 19 '18 at 02:19
  • I am actually not hiding the "Home" link. There is one partial View _header.html.erb, which contains the code. The IF statement controls what gets displayed based on log in status. However, once logged in the "Log in" link continues to show (and it shouldn't because the user has already logged in). If I am able to remove "Home" and "Help", I should be able to rearrange them so the second part is not so hard. –  Jul 19 '18 at 02:49

3 Answers3

1

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

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
1

Above answers are correct but its old method, you can do it without if else condition. rails provide built in link_to_unless helper . please check below code. you can arrange menus as per your requirement.

Not Tested

<ul class="nav">
  <li><%= link_to_unless(logged_in?, 'Log in', login_path){} %></li>
  <li><%= link_to "Home", root_path %></li>
  <li><%= link_to "Help", help_path %></li>
</ul>

Let me know if its not work

Vishal
  • 7,113
  • 6
  • 31
  • 61
0

You can do an if else statement to help you here.

<ul class="nav">
  <% if logged_in? %>
    <li><%= link_to "Home", root_path %></li>
  <% else %>
    <li><%= link_to "Log in", login_path %></li>
    <li><%= link_to "Help", help_path %></li>
  <% end %>
</ul>
ddonche
  • 1,065
  • 2
  • 11
  • 24
  • Your first two are set to show whether a user is logged in or not, so they show no matter what. – ddonche Jul 19 '18 at 03:52