Search code examples
ruby-on-railsruby-on-rails-4link-to

link_to_if throwing an error


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?


Solution

  • 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 %>