Aleksandr
Aleksandr

Reputation: 59

function nil.id/0 is undefined - Elixir, Phoenix

I can't figure out how to do the check correctly to hide the actions from the user

<%= if @current_user.id == @post.user_id do %>
  <span>
    <%= link "Edit", to: Routes.post_path(@conn, :edit, @post) %>
  </span>
  <span>
    <%= link "Delete", to: Routes.post_path(@conn, :delete, @post), method: :delete, data: [confirm: "Are you sure"] %>
  </span>
<% end %>

When the user is not logged in, this error appears:

UndefinedFunctionError at GET /posts/1 function nil.id/0 is undefined

Upvotes: 1

Views: 252

Answers (1)

sabiwara
sabiwara

Reputation: 3134

In this case, your @current_user is nil, so Elixir tries to run nil.id which fails.

You could probably solve your issue by checking for nil first:

<%= if @current_user && @current_user.id == @post.user_id do %>

The error message is a bit confusing because nil is also an atom, and the a.b syntax has two uses in Elixir:

  • accessing an atom key :b on a map/struct a (what you are trying to do)
  • calling the a.b() function, with a being a module atom

nil also being an atom, it gets interpreted as nil.id(), but the nil.id/0 function doesn't exist since nil is not an actual module.

Upvotes: 8

Related Questions