Home link_to_if throwing an error
Reply: 2

link_to_if throwing an error

john seymour
1#
john seymour Published in 2018-02-04 15:03:27Z

Im trying to fathom out link_to_if,

While calling:

<%= link_to_if(!current_user.nil?, "My profile", profile_path(current_user.profile)) %> <br>
<%= link_to_if(!current_user.nil?, "Edit profile", edit_profile_path(current_user.id) {}) %> <br>

Its throwing this error.

undefined method `profile' for nil:NilClass

of course because i have logged out but shouldn't the link_to_if stop profile_path(current_user.profile) from being called or i have i implemented it incorrectly?

Sergio Tulentsev
2#
Sergio Tulentsev Reply to 2018-02-04 15:23:48Z

but shouldn't the link_to_if stop

link_to_if hasn't even "started" yet. Before calling a method, all its arguments are evaluated. In this case, both condition AND the profile_path (which fails). You should wrap the link in an external conditional.

<% if current_user %>
  <%= link_to "My profile", profile_path(current_user.profile) %>
<% end %>
fool-dev
3#
fool-dev Reply to 2018-02-05 05:20:15Z

Try to the following

If you need without external condition then looks like this

<%= link_to_unless(current_user.nil?, "My profile", profile_path(current_user.profile)) %>

Or

<% if current_user %>
   <%= link_to "My profile", profile_path(current_user.profile) %>
<% end %>

Hope it helps

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324509 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO