Do I always need to add if @user in this?
In Pattern 1, it doesn’t have if @user so it returns ‘nil’ error when the user was deleted.
In Pattern 2, it won’t return ‘nil’ error but it’s too anoying to add this every single line of these things:(
Isn’t there any smart way to solve this kind of ‘nil’ error?
and I just want to display “[Not Found User]” when the user was deleted.
view/posts/show.html.erb
#Pattern 1
<%= display_nickname(@user.nickname) %>
#Pattern 2
<%= display_nickname(@user.nickname) if @user %>
application_helper.rb
def display_nickname(nickname)
if !nickname.nil?
return nickname
end
"[Not Found User]"
end
You can write your helper like that: