Hi!
I am studying elixir and phoenix from Udemy course.
What I was trying to do is this,
User creates a new topic for discussion, and only user that creates topic can edit and delete them from indexi page.
So in index.html.eex
<ul class="collection">
<%= for topic <- @topics do %>
<li class="collection-item">
<%= link topic.title, to: topic_path(@conn, :show, topic) %>
**<% if @conn.assigns.user.id == topic.user_id do %>**
<div class="right">
<%= link "Edit", to: topic_path(@conn, :edit, topic)%>
<%= link "Delete", to: topic_path(@conn, :delete, topic), method: :delete %>
</div>
<% end %>
</li>
<% end %>
</ul>
in topic controller
def index(conn, _params) do
topics = Repo.all(Topic)
render conn, "index.html", topics: topics
end
and I got
function nil.id/0 is undefined or private
I think it is because of assigns.user is nil before sign in, in this line @conn.assigns.user.id.
So How can I solve this problem?
Something like this might be the easiest solution.
<%= unless is_nil @conn.assigns.user and @conn.assigns.user.id == topic.user_id do %>
<div class="right">
<%= link "Edit", to: topic_path(@conn, :edit, topic)%>
<%= link "Delete", to: topic_path(@conn, :delete, topic), method: :delete %>
</div>
<% end %>
<%= if @conn[:assigns][:user][:id] == topic.user_id do %>
…
<% end %>
This uses the fact, that nil[:foo] will return nil.
But to be honest, I’d create a helper function current_user which does exactly that, return either the currently logged in user or a value signaling that no user is currently logged in.
Its not that you have less to type, but its easier to read…