Mac OS Catalina 10.15.7 ruby 2.6 series rails 6.0 series
It was one day when I was making an original app as a portfolio for changing jobs. When a non-logged-in user makes a request to transition to the details page locally, the following error occurs
From the conclusion, it was solved by adding the condition of user_signed_in? &&.
Code at the time of error
ruby:show.html.erb
<% if current_user.id == @post.user.id %>
<div class = "btn-contents">
<%= link_to 'To edit', edit_post_path(@post.id), class: "edit-btn"%>
<%= link_to 'delete', "#", class: "delete-btn"%>
</div>
<% end %>
Code after error resolution
ruby:show.html.erb
<% if user_signed_in? && current_user.id == @post.user.id %>
<div class = "btn-contents">
<%= link_to 'To edit', edit_post_path(@post.id), class: "edit-btn"%>
<%= link_to 'delete', "#", class: "delete-btn"%>
</div>
<% end %>
It was a very dull story.
The cause was that the current_user method was also used when requesting a non-logged-in user because I forgot the conditions for the non-logged-in user.
current_user is a method that can get the information of the user who is currently logged in, but in this case, I tried to get the login information even though I was not logged in.
Therefore, it is said that rails teacher got angry with a feeling like "current_user ??? I don't have such information because I haven't logged in in the first place ???".
So, first of all, by using the user_signed_in? Method in the previous condition, false will be returned if you are not logged in. That way, if you haven't logged in, you won't be able to transition to the following conditions, and the error will be resolved. (The description A && B does not refer to B's condition if A's condition is false)
As a countermeasure, I think that "somehow stop understanding the method".
The cause of the error is as described above, but I think the root cause is "I used the method with the intention of somehow remembering and understanding it." I'll be careful,,,
Recommended Posts