I have a page where I'm checking to see if the database column public
is true or if a user is admin.
<% if @user.public || current_user.admin %>
... users page ...
<% end %>
The issue right now is that if I'm not logged in, then its checking if current_user.admin
is true, so I get a NoMethodError
undefined method `admin' for nil:NilClass
What is the most logical syntax so I can check if its public or admin if I'm not logged in, so it should direct to a noticed page instead of getting this error.
Thanks
You need to check if current user
is set before checking whether it's an admin
:
if @user.public || (current_user && current_user.admin)
Ruby 2.3.0 introduced the Safe Navigation operator ( &.
).
This makes the code even nicer:
if @user.public || current_user&.admin
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.