Parry Parry - 1 month ago 8
Ruby Question

using link_to inside if

I have a user_authenticate method which is setting the @current_user based on session. I have a navbar layout which contains the navigation links. I want to hide one of the links and show it only if user id is 8 (which is admin). I have written the layout like this.

<div align="center" style="width: 90%">
<nav class="navbar navbar-inverse" role="navigation">
<%= link_to "Home", '/', :class => "btn btn-default navbar-btn"%>
<%= link_to "Currency Master", currencies_url, :class => "btn btn-default navbar-btn"%>
<%= link_to "Receipts", receipts_url, :class => "btn btn-default navbar-btn"%>
<%= link_to "Expenses", expenses_url, :class => "btn btn-default navbar-btn"%>
<%= link_to "Exchange", exchanges_url, :class => "btn btn-default navbar-btn"%>
<% if @current_user.id == 8 %><%= link_to "Report", reports_url, :class => "btn btn-default navbar-btn" %>
<% end %>
</nav>


The code works fine that it shows the "Report"button on navbar only of the user id is 8. But as soon as I click on the link I get following error.

undefined method `id' for nil:NilClass
Extracted source (around line #8):
6
7
8
9
10

<%= link_to "Expenses", expenses_url, :class => "btn btn-default navbar-btn"%>
<%= link_to "Exchange", exchanges_url, :class => "btn btn-default navbar-btn"%>
<% if @current_user.id == 8 %><%= link_to "Report", reports_url, :class => "btn btn-default navbar-btn" %>
<% end %>
</nav>

Answer

You are checking @current_user.id even if @current_user is not present. so it is giving an error.

First check the presence of current_user and then check id,

@current_user.present? && @current_user.id == 8

Change this line,

<% if @current_user.id == 8 %><%= link_to "Report", reports_url, :class => "btn btn-default navbar-btn" %>
  <% end %>

to,

<% if (@current_user.present? && @current_user.id == 8) %><%= link_to "Report", reports_url, :class => "btn btn-default navbar-btn" %>
  <% end %>