There were some points to be aware of when combining the if statement and the logical operator, so I will summarize them.
if conditional expression
#Processing when the conditional expression is true
else
#Processing when the conditional expression is false
end
&& → and ||→ or
if conditional expression 1&&Conditional expression 2
#Processing when conditional expression 1 and conditional expression 2 are true
else
#Processing when even one of the conditional expressions has false
end
Looking at it in detail, if conditional expression 1 is false, the code of conditional expression 2 is not read in the first place. In particular,
<% if user_signed_in? && @message.user.id == current_user.id %>
<% if @message.user.id == current_user.id && user_signed_in? %>
When using devise to separate the display between logged-in state and non-logged-in state, If you are logged in, neither code will cause an error. However, if you are not logged in, The code above doesn't cause an error, but the code below does.
The reason is that @ message.user.id
and current_user.id
are not entered unless they are logged in, and it is not possible to determine whether they are equal with ==
in the first place.
On the other hand, in the above formula, if you are not logged in at the time of ʻuser_signed_in?,
false is returned, so you do not have to use the code after
&& `for discrimination.
Recommended Posts